console.log({ myVariable });
Publikováno: 19.11.2020
I think this might be my most popular tweet of all time, but I’m not sure how to verify that these days. I’ll restate this neat little trick here because blogging is cool and fun.
I used to do this a lot while debugging JavaScript:
console.log("myVariable: ", myVariable);
But now I do this because it’s just easier to type quickly:
console.log({ myVariable });
And you don’t miss out on anything in DevTools:
Now that this is a blog post, I … Read article “console.log({ myVariable });”
The post console.log({ myVariable }); appeared first on CSS-Tricks.
You can support CSS-Tricks by being an MVP Supporter.
I think this might be my most popular tweet of all time, but I’m not sure how to verify that these days. I’ll restate this neat little trick here because blogging is cool and fun.
I used to do this a lot while debugging JavaScript:
console.log("myVariable: ", myVariable);
But now I do this because it’s just easier to type quickly:
console.log({ myVariable });
And you don’t miss out on anything in DevTools:
Now that this is a blog post, I can elaborate a smidge…
The output display there (and really, console.log
itself) is a DevTools thing, but the syntax isn’t. By using curly brackets in JavaScript, I’m creating an object. I don’t have to assign an object to anything, it can just be.
{
foo: "bar"
}
You see that a lot when passing an object to a function, like myFunction({ config: options });
. The “trick” is that when you’re making an object, you can “shorthand” it by providing only a variable, which makes it implied). So like:
const fruit = "apple";
// Shorthand
let x = {
fruit
}
console.log(x);
// Normal way, literally the same exact thing
x = {
"fruit": fruit
}
console.log(x); // identical
When you have a variable and you log it like console.log({ myVariable });
you’re using that shorthand object creation syntax and it gets logged like the object it becomes.
One strike against this idea is that sometimes DevTools chooses to output it as ▶ Object and you have to click to open to see the value. I don’t know what the heuristics are of when it chooses to do that and when it doesn’t. If you don’t like that, or the output format of an object in general, you might prefer the console.table({ myVariable });
format:
The post console.log({ myVariable }); appeared first on CSS-Tricks.
You can support CSS-Tricks by being an MVP Supporter.