Console.log vs printing out variable - javascript

How come when I use console.log to print out a value in the console window for a string it is not in quotes, but when I just output the variable in the console, it prints quotes. Is there any particular reason for this?
var test = “hello”;
test;
Output : “hello”
Console.log(test);
Output: hello

Well , see like this.
var test = "hello";
test; // This is object in self and what is it,
// it is a string in literal
// Output comes only from debugger , when you input direct.
// test; this line have no output to the console
// Output : "hello" NO
//console.log(test); // console.log already print string (in native/string is output) but also print objects.
// Output: hello YES
console.log( test + " this is the test")
// See output it is a very clear
// hello this is the test

The default behavior is for strings to be represented along with quotes in the console.
a = 'hi';
a
// returns "hi"
The console api is different and an exception.
console.log(object [, object, ...])
Displays a message in the console. Pass one or more objects to this method. Each object is evaluated and concatenated into a space-delimited string.
So it returns a space-delimited, concatenated string. Which means it will always be a string. Since its always a string, we can do away with the quotes. I suppose the console devs let it be that way to make the point that console.log() will always return the same type (string). Adding quotes might imply the possibility that it could return other things, so it seems to be a UX thing for the console.

Javascript is dynamically typed which means a variable can store any type of value at any time. If you call a variable storing a string (which is test in your case) it prints out the value "Hello" indicating its a string and returns a string datatype, which is preety straightforward. But numbers can also be strings like var a = "5". On the other hand console.log() simply prints the value inside the variable and by default returns undefined.
var a = "hello";
// To check the return type of variable a which is string
console.log(typeof(a));
// To check the return type of console.log() which is undefined
console.log(typeof(console.log(a)));

Related

Javascript, what happens when we assign value to read-only data property such as string length?

Suppose we have a string, length is read-only data property of string. What happen if we unintentionally assign value to length property of string? Why javaScript return those value as a result?
for example if we run this part of code:
var str="test";
console.log(str.length)
console.log(str.length=3)
output should be like this:
4
3
the third line of code returns 3, My question is why assignment in javaScript returns right side of operand not left side of it?
The assignment operator always returns the right-hand value. Hence, passing the expression inside the console.log function returns the right-hand value, in your case 3.
Assigning any value to the length property of a string has no effect.
let myString = "Hello,World!";
myString.length = 4;
console.log(myString);
// expected output: "Hello,World!"
console.log(myString.length);
// expected output: 12

Javascript String Array-Like-Object behaviour

When I run above code in Chrome dev console, I do not get any error. But when same code runs via js loaded on a webpage I receive this exception -
Cannot create property 'name' on string 'some string'
Can someone please tell me why there is different behaviour in above 2 cases?
Your webpage must be running that snippet of code in strict mode, in which assigning to properties of a string will throw an error:
'use strict';
const str = 'foo';
str.bar = 'bar';
In sloppy mode, it'll just fail silently:
const str = 'foo';
str.bar = 'bar';
Strings are a value objects as in they have a value not a reference to an instance of an object, they cannot have properties set with a["name"] like reference objects can.
a[3] is the 4th character in the string, a[0] being the first.
Let's see this case
const a = "a"
Object.isFrozen(a) // true
const b = new String("b")
Object.isFrozen(b) // false
From this section, we could see that String objects are not necessarily frozen. Only those string literals are frozen (I think it's because they are shared in a pool. If they are not frozen, you can create properties on one place to affect the code elsewhere) However, the explicitly constructed String objects are independent from the pool, thus not frozen.

Why does console.log log strings with quotes in some cases?

I am running these examples of Node.js v10.5.0. When I only print strings with it, it prints the strings without surrounding quotes.
> console.log('foo', 'bar')
foo bar
undefined
But when I print strings and numbers together, then it prints strings with surrounding quotes.
> console.log(1, 'foo', 'bar')
1 'foo' 'bar'
undefined
Why does this difference occur? I was expecting it to print the following in the second example:
1 foo bar
Similar behavior can be observed with Chrome 70.
It looks like console.log() chooses to show string in quotes when there are arguments of number type but then these examples print all strings without quotes even when numbers are involved:
> console.log('foo', 'bar', 1)
foo bar 1
undefined
> console.log('foo', 1, 'bar')
foo 1 bar
undefined
What's going on here? Why does console.log() print strings with quotes in some cases and not in other cases?
This seems like a deliberate choice by the Chrome team. There is no standard for how console.log works in different environments.
There's not a legitimate standard yet for console.log but most browsers, including Chrome (i.e. Chromium), use the working group specification (WHATWG):
https://console.spec.whatwg.org/#logger
According to this spec, if you have differing numbers of parameters then different methods are used to output the data, according to the current specification:
2.1 Logger(logLevel, args)
If args is empty, return.
Let first be args[0].
Let rest be all elements following first in args.
If rest is empty, perform Printer(logLevel, « first ») and return.
If first does not contain any format specifiers, perform
Printer(logLevel, args).
Otherwise, perform Printer(logLevel, Formatter(args)).
Return undefined.
Ultimately, the number of parameters determine the methods that are used to output information. Specifically, in your example the first parameter can not contain a format specifier because it's a number so it gets passed to Printer() but if the first parameter is a string then it gets passed to Formatter().
So, you get different output depending on order:
> console.log('hello',1,'hello')
hello 1 hello
versus
> console.log(1,'hello','hello')
1 "hello" "hello"
Ultimately, how those methods output information is implementation/browser dependent:
How the implementation prints args is up to the implementation, but
implementations should separate the objects by a space or something
similar, as that has become a developer expectation.

Why does the console print undefined when I assign a variable?

Hey pretty simple task I am trying to do.... I'm trying to take the text in my textbox and assign it to a var. When I run without the var I am getting text but if I assign it to a var I get undefined. Could someone explain this to me as it is very confusing to me?
TL;DR: It does not.
You can see content of your variable test, il will output the same thing as before. In fact it is the variable assignement that returns the undefined you see here.
For instance:
var test = 'Hello' // => undefined
test // => 'Hello'
Another case is printing your variable with console.log. If you do so, the return value will be undefined but the output will be your variable content (Hello here).
console.log(test) // return: undefined / print: Hello
What's returning undefined is the statement itself that you entered into the console, NOT the value of var text.
To see that console.log(text) or simply type text in the console.

Different behaviour of json.parse for same input?

This question is about
why the outputs are different
not how can i achieve the proper output.
I am unable to understand why the output of following two scenarios is not the same, even if I am giving the same argument to the JSON.parse() function.
FIRST scenario
obj = {a:"asdf"};
var newObj = JSON.parse(JSON.stringify(obj)); //newObj = {a:"asdf"}
Debugging
SECOND scenario
var newObj = JSON.parse("{"a":"asdf"}"); //this gives an error
The problem is with quotes.
var newObj = JSON.parse('{"a":"asdf"}');
should work correctly.
In Javascript, we use quotes (single or double) to represent a String. When you want to define a String that contains quotes, then you must use different quotes, or escape the quotes using backslash \ character.
var newObj = JSON.parse("{\"a\":\"asdf\"}");
also works fine.
You might think that
var newObj = JSON.parse("{'a':'asdf'}");
would work, but no. In JSON, strings are defined using Double quotes only.
why the outputs are different
Because the inputs are different.
FIRST scenario
obj = {a:"asdf"};
var newObj = JSON.parse(JSON.stringify(obj));
Here the input parameter of JSON.parse is JSON.stringify(obj)and this is a string that reads {"a":"asdf"}.
SECOND scenario
var newObj = JSON.parse("{"a":"asdf"}");
Here the input parameter of JSON.parse is a string that reads { and the rest is broken code.
Confusion arises because the console debugger decides all strings should be shown on the console encapsulated with a ", but this is just a way for the console to tell you that this value is of type String. It does not check whether you have " inside and escape them.
The encapsulating " are not part of the string, only a way of telling it is a string.
If console.logging JSON.stringify(obj) gets you "{"a":"asdf"}" try doing alert instead, or document.write. These will not add extra " and you will see that the value of JSON.stringify(obj) is actually {"a":"asdf"}, not "{"a":"asdf"}".
<html><head></head><body>
<script>
function JSONparse(string) {
document.write(string);
alert(string);
console.log(string);
return JSON.parse(string);
}
var obj = {a:"asdf"};
result = JSONparse(JSON.stringify(obj));
</script>
</body></html>
var newObj = JSON.parse('{"a":"asdf"}');

Categories