Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript variable: var a =(3,4,7); [duplicate]

Tags:

javascript

var a =(3,4,7);
console.log(a);  // Output is 7

Can you please explain how we are getting output 7?

like image 692
Akshay Barot Avatar asked May 11 '18 07:05

Akshay Barot


People also ask

What is the VAR in JavaScript?

var is the keyword that tells JavaScript you're declaring a variable. x is the name of that variable. = is the operator that tells JavaScript a value is coming up next. 100 is the value for the variable to store.

When should I use VAR in JavaScript?

Always declare JavaScript variables with var , let , or const . The var keyword is used in all JavaScript code from 1995 to 2015. The let and const keywords were added to JavaScript in 2015. If you want your code to run in older browser, you must use var .

How do you declare a variable in JavaScript?

Use the reserved keyword var to declare a variable in JavaScript. Syntax: var <variable-name>; var <variable-name> = <value>; A variable must have a unique name.

Why VAR is not used in JavaScript?

The Var Keyword This means that if a variable is defined in a loop or in an if statement it can be accessed outside the block and accidentally redefined leading to a buggy program. As a general rule, you should avoid using the var keyword.


1 Answers

It's called comma operator. By wrapping the right hand expression in parentheses we create a group and it is evaluated each of its operands and returns the last value.

From MDN

The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.

The comma operator is useful when you want to write a minifier and need to shrink the code.

For instance,

print = () => console.log('add')
add_proc = (a,b) => a + b

function add(a, b){
  if(a && b){
      print();
      return add_proc(a,b)
  }
  else
  {
     return 0
  }
}

console.log(add(1,2));

could be minified using comma operator as below:

print = () => console.log('add')
add_proc = (a,b) => a + b

add = (a, b)=> a && b ?(print(),add_proc(a, b)):0

console.log(add(1,2));
like image 63
Mihai Alexandru-Ionut Avatar answered Sep 28 '22 09:09

Mihai Alexandru-Ionut