I'm trying to adapt some code that contains this line:
var nav = document.getElementById('access_nav'),
body = document.body;
Could someone help me understand what I'm looking at?
At first I thought it was two variables being declared, 'nav' and 'body', but then I saw the comma, and I wondered if it was a variable 'nav' with two arguments.
Something else?
-
4It's what you think it is, but it is evil.John Hascall– John Hascall2017年03月02日 23:56:30 +00:00Commented Mar 2, 2017 at 23:56
-
nav and body both is variable nav is a element with id="access_nav" and body is body tag is that clear ?XYZ– XYZ2017年03月03日 00:07:08 +00:00Commented Mar 3, 2017 at 0:07
-
2also you can every time not able to understanding put into console.log example console.log('what is this:', body)XYZ– XYZ2017年03月03日 00:08:42 +00:00Commented Mar 3, 2017 at 0:08
4 Answers 4
That's two variables, you are right.
It is strictly equivalent to
var nav = document.getElementById('access_nav');
var body = document.body;
Which (in my opinion), is clearer. The simple existence of your question is enough for me to not like this notation.
Comments
It's just a shortcut to declare variables. It equals to:
var nav = document.getElementById('access_nav');
var body = document.body;
Comments
We have no 2-argument-variable in javascript. Its just a shorthand for declaring variables & from the POV of its context, Both following are the same:
this:
var nav = document.getElementById('access_nav'),
body = document.body;
and this:
var nav = document.getElementById('access_nav');
var body = document.body;
Comments
@Bewildered
It is a multiple variable declaration in one line.
var nav = document.getElementById('access_nav'),
body = document.body;
The traditional JavaScript version of these declarations is:
var nav = document.getElementById('access_nav'); // Grab an HTML element with an ID 'access_nav'
var body = document.body; // Store entire body of the document in a variable. Useful when you need to some later operations on it.