Which is the better way to take variable into function

Hi guys,

I’ve to pick data from a PHP function using one of the methods like below, but I can’t decide which one is better:

<script>
	var data = "<?php echo $data; ?>";
	(function blahBLAHandBlah() {
		// do something with data
	})();
</script>

VS

<div id="data-item">
	<?php echo $data; ?>
</div>
<script>
	(function blahBLAHandBlah() {
		var data = document.getElementById('data-item'),
			value = data.innerHTML;
		// do something with data
	})();
</script>

The data would be fed into a JavaScript function in order to process it.

Someone has said global variable is bad.
The others say don’t touch DOM.

In term of better performance, which one is better. I’ve to get data from method like these all over the site.

PS. The data element will not be shown.

Thank you,

Google uses the first method, for what it’s worth. Global variables aren’t inherently bad, but misusing them is very easily done. If you’re passing multiple values it’s probably best to bind them into one array and json_encode that array. I would not normally create a DOM object for it, but it might be appropriate in some contexts such as a form, in which case placing the value in a hidden input field is the way to go.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.