Skip to content

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

2 thoughts on “JavaScript access variable outside the callback | Example code”

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading