0

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?

kind user
42k8 gold badges69 silver badges78 bronze badges
asked Mar 2, 2017 at 23:53
3
  • 4
    It's what you think it is, but it is evil. Commented 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 ? Commented Mar 3, 2017 at 0:07
  • 2
    also you can every time not able to understanding put into console.log example console.log('what is this:', body) Commented Mar 3, 2017 at 0:08

4 Answers 4

3

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.

answered Mar 2, 2017 at 23:54
Sign up to request clarification or add additional context in comments.

Comments

3

It's just a shortcut to declare variables. It equals to:

var nav = document.getElementById('access_nav');
var body = document.body;
answered Mar 2, 2017 at 23:54

Comments

2

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;
answered Mar 3, 2017 at 0:02

Comments

2

@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.
answered Mar 3, 2017 at 0:05

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.