JavaScript access variable outside the callback | Example code

You can define the variable in a function and pass it to the callback function in JavaScript. The callback function should have a parameter option.

Access to a variable outside of a callback function in javascript

HTML example code:-

<html>
<body>

	<script>
		function displayResult(res) {
			console.log(res)
		}

		function addNum(num1, num2, myCallback) {
			var sum;
			sum = num1 + num2;

			myCallback(sum);
		}

		// Test case
		addNum(10, 5, displayResult);


	</script>
</body>
</html>

Output:

JavaScript access variable outside the callback

Do comment if you have any doubts and suggestion on this JS variable topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.