Variables and Data Types in Javascript

JavaScript , Tue Dec 27 2022

    Variables

    Variables are used to store information to be referenced and manipulated in a computer program. They also provide a way of giving variables a descriptive name, so our programs can be understood more clearly by the reader and ourselves.

    It is helpful to think of variables as containers that hold information. Their sole purpose is to label and store data in memory. This data can then be used through the entirety of your program.

    Variables in JavaScript are containers which hold reusable data. In other words, they are units of storage, like some sort of box into which we can put data.

    Here are the following three simple steps to creating a variable:

    • Create a variable with the appropriate name.
    • Store your value in it.
    • Retrieve and use the stored value from the variable.

    The values that we store in our variables can come in the form of predefined Data Types.

    The computer needs to know of which type is our value so it can manipulate it properly.

    So, how can we create a variable? We need a var keyword, a variable name and the value we want to assign to that variable:

    var variableName = 'Hello, World!';

    Just a note, semicolons are used to terminate a line in javascript. They are optional, but omitting them can lead to undesired consequences on rare occasions. So it's a good practice to always put them at the end!

    In earlier versions of JavaScript, variables were solely declared using the var keyword followed by the name of the variable and a semicolon. This is how we would do it.

    var variableName = '';

    After ES6 (a newer version of JavaScript) we now have two new ways to declare a variable: let and const. We can take a look at both of them one by one.

    The variable type let shares lots of similarities with var but unlike var it has some scope constraints. The scope is out of "scope" of this introductory video but we will explain it in great detail in a later video! The only thing that you need to know right now is that let is the preferred way of creating variables in modern JavaScript.

    let variableName = '';

    Const is another variable type assigned to data whose value cannot and will not change throught the script.

    const variableName = '';

    The variableName is the name of the variable which you can freely choose.

    What do you think, can we name our variables literally anything?

    We have a few criteria when it comes to creating variable names, also known as identifiers.

    We have a few rules when it comes to creating an identifier in JavaScript:

    • The name of the identifier must be unique
    • The name of the identifier should not be any reserved JavaScript keyword (for example, we cannot declare a variable like this: var let = 0h;)
    • The first character must be a letter, an underscore (_), or a dollar sign ($). Subsequent characters may be any letter or digit or an underscore or dollar sign.

    The first character must be a letter, an underscore (_), or a dollar sign ($). Subsequent characters may be any letter or digit or an underscore or dollar sign.

    To recap, there are three different ways to make (or declare) a variable: var, let and const.

    Const when variable is going to be constant and let when we plan on changing it!

    Let's move on to data types to see what kind of data can we store inside of variables!

    Data Types

    As mentioned, we can store values in variables. And these values need to be in the form of one of the predefined data types.

    The concept of a value is somewhat abstract, especially to someone doing programming for the first time.

    There are a few "types" of values, called data types. Let's go through them one by one, and then we're going to explain each one in detail.

    We can separate data types of current JavaScript Standard in two groups:

    • Primitivy Data Types
    • Non-Primitivy Data Types

    Primitivy Data Types

    Number 5, 6.5, 7 etc
    String "Hello everyone" etc
    Boolean true or false
    Null represents null i.e. no value at all
    Undefined A variable that has not been assigned a value is undefined.
    Symbol used as an identifier for object properties.

    Non-Primitivy Data Types

    Object instance through which we can access members
    Array group of similar values
    RegExp represents regular expression

    Comments

    A comment is text in the code which is not read while we're running the code. You should write comments to explain what your code does.

    Comments make your code easier to read and understand. They can help you and others who read your code.

    There are two types of comments: multi-line and single-line comments.

    • Multi-line comments
    • Single-line comments

    Multi-line comments

    To write a comment that stretches over more than one line, you can use a multi-line comment, starting with the

    /* characters and ending with */

    closing it into a neat little rectangle. Anything between these characters is not processed by the JavaScript interpreter.

    Multi-line comments are often used for descriptions of how script works.

    Single-line comments

    In a single-line comment, anything that follows the two forward slash characters on that line will not be processed by the JavaScript interpreter.

    // single line comment

    Single line comments are often used for short descriptions of what the code is doing.

    Good use of comments will help you if you come back to your code after several days or months. They also help those who are new to your code.

    Strings

    'String' is a sequence of characters. String is a data type used to represent text.

    Strings are simply fields of text. To wrap these words, we use quotes. A string in JavaScript must be surrounded by quotes.

    In JavaScript, there are 3 types of quotes: Single quotes, Double quotes, Backticks

    const singleQuote = 'Hello, everyone!'; const doubleQuotes = "Hello, everyone!";

    Double and single quotes are "simple" quotes. There's practically no difference between them.

    Backticks are "extended functionality" quotes. They allow us to embed variables & expressions into a string by wrapping them in ${…}

    const backticks = `Hello! ${2 + 2}`;

    The expression inside ${…} is evaluated and the result becomes a part of the string.

    We can put anything in there: a variable like name or an arithmetical expression like 1 + 2 or something more complex.

    It is important to note that we can inspect the type of each value by writing tyepof before the value.

    Numbers

    JavaScript is real friendly when it comes to numbers, because you don't have to specify the type of number.

    We call this behavior untyped. JavaScript is untyped because determining whether a number is an integer or a decimal(float) is taken care of by the language's runtime environment.

    For example, in traditional programming languages like C, we'd have declare the type of the number we'd like to use. Like this:

    int wholeNumber = 5;
    float decimalNumber = 0.5;

    In JavaScript, we can just say use plain old const or let and use any number we'd like:

    const wholeNumber = 5;
    const decimalNumber = 0.5;

    We just learned that the number type represents both integer and floating point numbers.

    There are many operations for numbers, e.g.

    • + Addition
    • - Subtraction
    • * Multiplication
    • / Division

    When we try to do some operations with values that are not numbers, most often, we will get NaN as a result. simply means, not a number, it represents a computational error.

    It is a result of an incorrect or an undefined mathematical operation.

    alert("this is a string" * 3);

    What do you think we would get if we do a typeof of NaN?

    console.log(typeof NaN);

    The type of NaN, which stands for Not a Number is, surprisingly, a number

    The reason for this is, in computing, NaN is actually technically a numeric data type. However, it is a numeric data type whose value cannot be represented using actual numbers.

    Don't overthink this too much, numbers are quite straight forward in JavaScript, let's move on to Booleans!

    Booleans

    Booelan represents a logical entity and can have only two values: true or false

    As you'll come to know, these are important values when it comes to adding logic to our programs. With just those two values, you can create a complex system of loops & conditions.

    This type is commonly used to store yes/no values:

    • true means "yes, correct"
    • false means "no, incorrect"

    const isCool = true;

    if(isCool) {
        console.log("Hi man, you're cool");
    } else {
        console.log("Oh..Hi..");
    }

    Boolean values also come as a result of comparisons.

    const age = 20;

    if(age >=18) {
        console.log("You may enter");
    }

    Null and Undefined

    Null

    This type has only one value: null.

    The special null value does not belong to any of the types described above. It forms a separate type of its own which contains only he null value

    let age = null;

    null is just a special value which represents "nothing", "empty" or "value unknown".

    The code above states that age is unknown or empty for some reason.

    UNDEFINED

    A variable that has not been assigned a value is undefined.

    The special value undefined also stands apart. It makes a type of its own, just like 'null'. The meaning of undefined is "value is not assigned".

    If a variable is declared, but not assigned, then its value is undefined by default:

    let x;
    console.log(tyepof NaN);

    Technically, it is possiable to assign undefined to any variable:

    let x = 123;
    x = undefined;
    alert(x); // "undefined"

    But I wouldn't recommend doing that. Normally, we use null to assign an "empty" or "unknown" value to a variable.

    And we use undefined for checks like seeing if a variable has been assigned.

    UNDEFINED VS NULL

    Many a times we often get confused on whats the difference between UNDEFINED and NULL.

    undefined means a variable has been declared but has not yet been assigned a value. On the other hand, null is an assignment value. It can be assigned to a variable as a representation of no value. Also, undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.

    Unassigned variables are initialised by JavaScript with a default value of undefined. JavaScript never sets a value to null. That must be done programmatically.

    Objects

    Object is the most important data-type and forms the building block for modern JavaScript.

    The object type is special. All other types are called "primitive" because their values can contain only a single thing (be it a string or a number or whatever).

    What I'm going to let you know for now is that objects in their simplest forms are used to group variables.

    For example, we can create a variable of name, and age:

    const name = 'John';
    const age = 25;

    These two variables in the current state are in no way related on to another.

    We can create an object called person and put them together:

    const person = {
        name: 'John',
        age: 25 }

    Now we know that both name and age belong to the same entity, the person. That is an object.

    As you can see, we declare it the same as all other variables and then put curly brackets inside of which goes the data.

    The one last thing that we can mention is that we can now extract specific values from that object using the dot notation:

    person.name
    person.age

    There are many other kinds of objects in JavaScript:

    • Array to store ordered data collections
    • Date to store the information about the date and time
    • Error to store the information about an error.

    ...And so on.

    They have their special features that we'll study later. Sometimes people say something like "Array type" or "Date type", but formally they are not types of their own, but belong to a single "object" data type.

    And they extend it in various ways.

    That's all that I'm going to let you know for now. Objects are complex concepts. First, let's master the easy things, and then we can get back to them later.

    Statically vs Dynamically Typed Languages

    There are two types of languages when it comes to data types:

    Statically typed language is where each variable and expression type is already known at compile time. Once a variable is declared to be of a certain data type, it cannot hold values of other data types. Example: C, C++, Java.

    Dynamically typed languages can receive different data types over time. In this all type checks are performed in a runtime, only when your program is executing.

    JavaScript is dynamically typed; variables in JS can receive different data types over time.

    A variable in JavaScript can contain any data. A variable can at one moment be a string and at another be a number, for example:

    let message = "Hello, World!";
    message = 123456;

    ... It's a completely valid syntax.