I’m very new to JavaScript, and have recently learned about declaring variables with var
. like var a = 12
or whatever. But, I came across a line in some code for a website I was reading through for fun which read var t={};
.
This was actually only the second line of code.
I can’t seem to find any explanation online anywhere for what it means to set a variable to equal a set of empty curly braces.
I thought it might be a way of declaring an array or something??
I’m very new to JavaScript, and have recently learned about declaring variables with var
. like var a = 12
or whatever. But, I came across a line in some code for a website I was reading through for fun which read var t={};
.
This was actually only the second line of code.
I can’t seem to find any explanation online anywhere for what it means to set a variable to equal a set of empty curly braces.
I thought it might be a way of declaring an array or something??
-
3
{}
is an empty object. – CertainPerformance Commented Oct 15, 2018 at 2:42
4 Answers
Reset to default 5This defines a variable as an empty object
var t = {}
This defines it as an empty array
var t = []
This defines it as a boolean
var t = true
This defines it as an empty string
var t = ''
This defines it as an integer(number)
var t = 0
These are the basic building blocks/data types of javascript. There are plenty of tutorials online which cover this in the first lesson.
https://javascript.info/object
https://javascript.info/types
An object is a collection of data, it can contain arrays, booleans, strings, integers and even other objects. Objects consist of key/value pairs:
var user = {
// the key here is name and the value is a string 'Tom'
name: 'Tom',
// the value can also be an integer
age: 23,
// or an array
interests: ['gaming','travel','guitar'],
// or a boolean
loggednIn: false,
// or a nested object
contact: {
email: '[email protected]',
number: 01296714100
}
}
var
is one keyword from javascript language, used to define variable. Below is an explanation from Mozilla Developer Network (MDN):
The var statement declares a variable, optionally initializing it to a value
Statement var t={};
means a new variable called t
defined with initialised value is {}
. The {}
is literal for empty object, more explanation.
TL;DR; empty object created, stored in newly created variable t
.
It works to initialize an object.
For example, if you declare:
var a = {}
and get the type using typeof(a)
you going to get object
.
Different to:
var b = 1
- typeof(b)
is equals to number
var c = foo
- typeof(c)
is equals to string
And as object you can declare more plex variables, like
var a = { 'stackoverflowName':'mrmins', 'url':'https://stackoverflow.', 'gender':'mygender'}
let user = new Object(); // "object constructor" syntax
let user = {}; // "object literal" syntax
Usually, the figure brackets {...} are used. That declaration is called an object literal.
Please go through the following article for more clarity https://javascript.info/object