Does the JavaScript expression will return something?
In the Node.js REPL:
> console.log("Hello World")
Hello World
undefined
the undefined
is the JavaScript function return. Because the JavaScript function always return something.
But when I try define a variable in REPL:
> var x = 11
undefined
There will print a undefined
too. whether the JavaScript var expression will return something too?
Yes, all JavaScript statements have a result, although often it's pretty much useless, and only available using eval
function - at least until do
expressions will be added to the language. For example.
>>> eval("if (true) 4; else 5;")
4
>>> eval("if (true) 4; else 5;")
5
>>> eval("for (let i = 0; i < 10; i++) 7")
7
>>> eval("for (let i = 0; i < 10; i++) {}")
undefined
>>> eval("var express = 4")
undefined
And so on, the exact values are specified in a language specification.
When you type something in either browser's console or Node.js REPL, the expression in enclosed in IIFE and executed. This IIFE returns the expression that you entered. So if your expression is not returning anything, it prints undefined
.
Imagine you typed:
console.log(1)
It is interpreted by Node.js REPL as:
(function() { return console.log(1) })()
Since it is not returning anything, it simply prints undefined
on console.
Now if you write a number (eg 1
) in REPL, it is interpreted as:
(function() { return 1 })()
This will print 1
as return value.
HTH
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.