After learning about Javascript in the article Basic Introduction Javascript for Beginners, learning about variables and data types is the next step to learning Javascript programming. Javascript has 3 types of variables, and some data types that used are similar to other programming languages.
Table of Contents
Explanation of Variables and Data Types
What are variables?
In computer programming, variables are a container for storing value or information. A variable is an identity that used to hold one or several values. This value can change throughout the program code. Technically, a variable refers to an address in computer memory. Each variable has a unique name as an identity.
What is the data type?
The data type is a type of data that can be processed by a computer to meet needs in programming. When declaring a variable or constant, you must be able to determine what data type is suitable for that variable. Whatever programming language used, Variables, and data types always be there.
Variables in Javascript Programming
On this occasion, we learn Javascript variables and data types. In general, how to declare a variable begins with the var keyword, but since ES6, Javascript has two new keywords, let and const for variable matters. Var keyword remains to maintain compatibility with previous versions. Then what’s the difference? When to use let and const? We will discuss this at the end of this article.
In this tutorial, we learn to create Javascript variables, print variables to output, refill/change values in variables, and delete variables from memory.
How to Create Variables in Javascript
How to generally create a Javascript variable using the var keyword then followed by the name of the variable and its value.
Example:
1 | var title = "Tutorial Javascript For Beginners" |
In the example above, we create a variable named title with a value in the form of a string: “Javascript Tutorial For Beginners.”
Other Example:
1 2 3 | var siteName = "Seegatesite" var url = "https://seegatesite.com" var postCount = 290 |
A brief description:
In the example above, we use lowercase letters with capital letters for variable names consisting of two or more syllables. Why? In Javascript, it is recommended to use camelCase in naming variables. You can replace it using the underscore, for example writing var siteName to var site_name. That won’t be a problem. However, most Javascript programmers use camelCase.
To declare a variable of type string, use quotation marks and to declare an integer type without quotes.
A variable can declared without value. If the blank variable worth as “undefined.”
Example:
1 | var siteName; |
How to Print the Contents of Javascript Variables
To display the contents of a variable, we can use several functions to display output such as:
- console.log() : displays output to the javascript console.
- document.write() : displays the output to an HTML document.
- alert() : displays the output to the dialog window.
The three functions above have discussed in the previous article “Getting to know Javascript for beginners.“
Example:
1 2 3 4 5 6 7 | var siteName = "Seegatesite" var postCount = 290 var urlName = "https://seegatesite.com" document.write("Name : " + siteName) document.write("Article : " + postCount) document.write("URL : " + urlName) alert("Welcome to " + siteName) |
Explanation:
In the example above, if the variable type is string, the operator (+) combine the string into one.
Change / edit values in a variable
Variables are mutable, meaning the stored value can be changed.
Example:
1 2 | var friendCount = 3 friendCount = 10 |
When changing data in a variable, there is no need to add the var keyword, because the var keyword is needed to declaring a new variable. So we type the variable name and change the value. If you add the var keyword, Javascript will create a new variable
How to Delete Variable in Javascript
Actually, in making applications in general, deletion of variables is rarely done. However, for applications that require accuracy in memory allocation, removal of variables needs to be done, so that memory usage is more optimal.
Removal of variables will be done with the delete keyword.
Example:
1 2 | siteName = "Seegatesite" delete siteName |
Then the siteName variable will disappear from memory.
Deleting variables can only be done on variables that are made without keywords (var or let). While variables created with var and let keywords will be automatically deleted. “
Javascript Data Type
Data types are types of data that can be stored in variables. There are several data types in Javascript programming:
- String
- Integer
- Float
- Boolean
- Object
What about the array data type? In javascript, array is the same as the data object type.
Javascript is a programming language that is dynamic typing, so we do not have to write the data type when creating variables.
Example:
1 2 3 | var siteName = "Seegatesite" var siteAge =6 var isActive = true |
Javascript will automatically recognize the data type that we provide in the variable.
In the example above :
- siteName is a string type
- siteAge is an integer type
- isActive with a boolean type.
To check the data type used, you can use typeof keywords.
Example:
1 2 3 | typeof siteName typeof siteAge typeof isActive |
The difference between var, let, const in the Javascript variable
Other article: Tutorial Simple CRUD Angular 5 And Lumen 5.6 For Beginners
Before ES6, there was only one way to create a variable, which is using the var keyword. But along with the development of the Javascript framework, there are some disadvantages if only using var to declare variables.
Some of the problems that arise from var:
- Reassign123var foo = 'im number one'var foo =' im number two'console.log(foo) // im number two
The difficulty of handling two or more variables with the same name (duplication). Javascript does not display an error message when a duplicate variable occurs, so it will be difficult for the developer if the project is quite complex - Hoisting123y= 25var yconsole.log(y) //result : 25
Why are the results 25? It’s because of hoisting. Hoisting problems in Javascript make programmers confused. - Scope
Block scope in Javascript is marked with a symbol {}. Scope means the distribution of programs, this often found on conditional statements IF, looping for, switch, while, etc. Logically, the variables in the scope must be private and cannot be read by other scopes. Unlike Javascript, if declaring a variable using var, var is a global variable even though it is in the scope. Because of the above problems so that new types of variables are developed, namely let and const.
Let
The way let works is almost the same as var, the difference is in the scope. Var is a function scope, while let is a block scope.
Let was used to correct some of the var flaws.
- Reassign123let foo ='im number one'let foo =' im number two' //=> TypeError: Duplicate declaration "foo"console.log(foo)
the result is type error, meaning that let won’t allow you to make duplicate variables - Hoisting123y= 25let yconsole.log(y) // Uncaught ReferenceError: Cannot access 'x' before initialization
The result is “Uncaught Reference Error: Cannot access ‘x’ before initialization.” Hoisting does not apply to let, because let must be defined before being assigned - Scope
Let is a block scope, so we don’t have to deal with the function to create a local variable
Const
Const or Constants are fixed variables, so the names and contents of variables cannot be changed.
1 2 3 4 | const pi = 3.14 pi = 300 // Uncaught TypeError: Assignment to constant variable.. const pi=312 // Uncaught SyntaxError: Identifier 'KEY' has already been declared var pi = 3.14 // Uncaught TypeError: Assignment to constant variable. |
Different if you use an Object data type, const variables cannot be reassigned, but the values and properties in the object can be changed. This is because the object in Javascript is mutable. What Is mutable? I will discuss in another time.
Example:
1 2 3 4 | const obj = { id:1, name:’Shane'} obj.location="United stated" console.log(obj) // { id:1, name:'jhon',location:'medan'} obj={} // Uncaught TypeError: Assignment to constant variable. |
Conclusion
- Variables and data types are two essential things that must be learned in any programming language.
- In Javascript, we do not have to write data types when creating variables, because Javascript is dynamic typing.
In declaring variables, you should:- It’s better to use let, use var for specific things because var is global
- use const for variables whose values are fixed
Next Tutorial : Tutorial Operator, Conditional Statement and Loops Javascript for Beginners
Leave a Reply