JavaScript Archives - KarthikTechBlog https://karthiktechblog.com/category/javascript/ Everyone can code! Fri, 10 Dec 2021 19:55:20 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.2 https://karthiktechblog.com/wp-content/uploads/2022/08/cropped-lsc-logo-png-new-3-32x32.png JavaScript Archives - KarthikTechBlog https://karthiktechblog.com/category/javascript/ 32 32 JavaScript Getting Started | Variables var, let, and const | Part 2 https://karthiktechblog.com/javascript/javascript-getting-started-variables-var-let-and-const-part-2/?utm_source=rss&utm_medium=rss&utm_campaign=javascript-getting-started-variables-var-let-and-const-part-2 https://karthiktechblog.com/javascript/javascript-getting-started-variables-var-let-and-const-part-2/#respond Fri, 10 Dec 2021 19:55:20 +0000 https://karthiktechblog.com/?p=973 Introduction In this JavaScript Getting Started, you will learn about JavaScript Variables var, let, and const along with their usage. Join me in learning variables and start using them in your work. What is a variable ? Any application that we write is going to be based on data. If we’re selling fruits, we need […]

The post JavaScript Getting Started | Variables var, let, and const | Part 2 appeared first on KarthikTechBlog.

]]>
Introduction

In this JavaScript Getting Started, you will learn about JavaScript Variables var, let, and const along with their usage. Join me in learning variables and start using them in your work.

JavaScript Getting Started | Variables var, let, and const | Part 2

What is a variable ?

Any application that we write is going to be based on data. If we’re selling fruits, we need data on the fruit name, the price, and all the data that belongs to an invoice or a purchase order. Likewise, if you consider your work is around car company then you need all car-related information such as engine, model, price, etc. I can talk about many such examples. All deals with data.

In JavaScript and most other programming languages, we use variables to hold this information. Data is stored in the computer memory. Let’s take an example. If you had to sell a car which is of price $20,000.                

That needs to be stored somewhere in the computer’s memory and typically, a memory address is a long,               complicated number. It would be very difficult if we had to use this long number to reference that value.

So instead we use a variable. In this case, we can use a variable called carPrice. So in this case we were using an English word to represent the number in the computer, and you can use words and characters from your own native language and name it in an understanding way.

There’s a special terminology we use in programming when you create a variable. It’s called declaring the variable.

Declaring Variables

 We declare variables to let Javascript know that we are going to work with variables. When we declare a variable, we use a keyword, let. A keyword is a special symbol that JavaScript knows about.

It performs some type of action. In this case, let allows us to declare a variable, and after the keyword let,  we have the variable name that we want to use and there are certain rules for creating variable names. we will talk about the variable naming shortly.

Keywords let and var

We have been using the var keyword in JavaScript. However, the var keyword has some limitations when it comes to scope. There are only two scopes for var which are the global scope and function scope. There is no block scope. This often becomes a bug for many developers.

what is scope then? The scope of the variable is the area of the program where it is legal to use. var has only two scopes as Global Scope and Function Scope. There is no block scope for var keyword.

javascript variable function scope
// var Keyword scope example
var doSomeWork = function (raining) {
    if (raining) {
        var weather = '65F';
    }
    return weather;
};

let keyword solve this problem.

let is a new Keyword in JavaScript and allows us to define variables.

// var Keyword scope example
var doSomeWork = function (raining) {
    if (raining) {
        var weather = '65F';
    }
    return weather;
};

// let Keyword scope example
var doSomeWork = function (raining) {
    if (raining) {
        let weather = '65F';
        return weather;
    }

    return '85F';
};

since variable “x” is available throughout the function there is no error. let the keyword makes the variable scoped to the condition and hence we got an error. Using such code through javascript runtime error stating no such variable exist.

All this confusion with the var keyword is because of the Hoisting. Hoisting is JavaScript’s default behavior of moving declarations to the top. You can read more here.

Another example is to use the let keyword in for loops.

JavaScript Getting Started | Variables let

Variable naming

  1. The name must contain only letters, digits, or the symbols $ and _
  2. The first character must not be a digit.

Try to provide a meaningful name and limit the length of the variable to a max of 15 characters.

example for variable naming

let $ = 20;
let _ = "John"
let _name$ = "name"

const Keyword

The const keyword is another addition in ECMA Script 6 (ES6). The idea of using this is to create and initialize a read-only variable. A variable that holds a constant value is something that you never change.

ES6 for const will have block scoping.

var constFuntion = function () {
    const max_size = 20;
    max_size = 20 + 20; // syntax error as you cannot assign value again;
}

Another difference with const and var keywords is you can define a variable more than once with the var keyword. However, you cannot do the same with the const keyword.

JavaScript Getting Started | Variables var, let, and const

JavaScript Getting Started: Table of contents

  1. Introduction and Setting up a local environment
  2. Variables and constants
  3. Types and Operators
  4. Program flow : conditions, comparision and different loops.
  5. Parameters : Default, Rest …Spread and templates
  6. Functions
  7. Objects and the DOM
  8. Arrarys
  9. Scope and Hoistings
  10. Classes (Advance)

Summary

This post JavaScript Getting Started covers Variables var, let, and const, how we declare variables, and the usage of var, let, and const keywords.

The post JavaScript Getting Started | Variables var, let, and const | Part 2 appeared first on KarthikTechBlog.

]]>
https://karthiktechblog.com/javascript/javascript-getting-started-variables-var-let-and-const-part-2/feed/ 0 973
JavaScript Getting Started | Introduction | Part 1 https://karthiktechblog.com/javascript/javascript-getting-started-introduction-part-1/?utm_source=rss&utm_medium=rss&utm_campaign=javascript-getting-started-introduction-part-1 https://karthiktechblog.com/javascript/javascript-getting-started-introduction-part-1/#comments Fri, 10 Dec 2021 15:03:04 +0000 https://karthiktechblog.com/?p=966 Introduction JavaScript is one of the most popular programming languages. JS is the top programming language, and it’s more than twice as popular as Python. JavaScript the ubiquitous language for the web, it’s reached beyond the web.  It now runs inside of database engines, web servers, game consoles, and refrigerators. Backward compatibility is important when […]

The post JavaScript Getting Started | Introduction | Part 1 appeared first on KarthikTechBlog.

]]>
Introduction

JavaScript is one of the most popular programming languages. JS is the top programming language, and it’s more than twice as popular as Python.

JavaScript: Getting Started | Introduction | Part 1

JavaScript the ubiquitous language for the web, it’s reached beyond the web.  It now runs inside of database engines, web servers, game consoles, and refrigerators. Backward compatibility is important when there is so much code depending on a language. However, ES6 has come to take it forward to the next level.

In this Javascript: Getting Started tutorial, you’ll know the very basics of JavaScript and you’ll be able to build simple programs for the web. No prior knowledge of programming is required for this course.

This Javascript: Getting started is for those who are completely new to programming. Also valuable for programmers who are just new to the JavaScript language.

Installing Development Software for Demo/Practice

In order to start working with Javascript, there’s certain software that needs to be installed on our machines.

We need to have GIT, Node.js and an IDE, in our case it is Visual Studio Code.

Steps to check and install softwares

Step 1: To check GIT is installed, just type "git --version" in the command prompt if you are using a windows machine. On a Mac, you would go to a terminal window.

If you did not find GIT installed on your machine (when you see Error), install the download from https://git-scm.com/ both for windows and mac downloads are present (scroll down and check to your right side).

Step 2: Next is we need to install node package manager or npm package manager which comes with a . bundle in Node.js. To check node is installed, execute the command "npm --version“. visit https://nodejs.org/en/ and install the LTS version when you see the error. At the time of this post, 16.13.1 is the LTS version.

Step 3: I will be using Visual Studio Code as an editor for all the demo. You can download that at code.visualstudio.com

Setting up project from GitHub

I have set up a sample “Hello World” project and that will be good to start with. It has everything that you need to start developing.

js-starter is the repository name in GitHub. Go to https://github.com/karthiktechblog/js-starter and click on clone or download. you may also clone the project in Visual Studio Code by using this URL https://github.com/karthiktechblog/js-starter.git

Inside the sample project, there is a file named package.json which contains the required dependency software to run the project. Go to the terminal window by clicking Terminal => New Terminal from the top menu or using the shortcut “ctrl + shift +”.

Now, run “npm install” command which will install the lite server, version 2.5.4. Run "npm run start" in your terminal to start the server.

Now, we get Hello World, and you can see that the lite server is running on localhost port 3000.

JavaScript: Getting Started | Introduction sample app demo

JavaScript Getting Started: Table of contents

  1. Introduction and Setting up a local environment
  2. Variables and constants
  3. Types and Operators
  4. Program flow : conditions, comparision and different loops.
  5. Parameters : Default, Rest …Spread and templates
  6. Functions
  7. Objects and the DOM
  8. Arrarys
  9. Scope and Hoistings
  10. Classes (Advance)

Summary

In this post, you learned JavaScript and how to kick start your learning journey along with me. Thanks for reading and in the next post, you will learn about variables and how to declare and use them.

The post JavaScript Getting Started | Introduction | Part 1 appeared first on KarthikTechBlog.

]]>
https://karthiktechblog.com/javascript/javascript-getting-started-introduction-part-1/feed/ 1 966
Destructuring JavaScript objects and deep object assignment https://karthiktechblog.com/javascript/destructuring-javascript-objects-and-deep-object-assignment/?utm_source=rss&utm_medium=rss&utm_campaign=destructuring-javascript-objects-and-deep-object-assignment https://karthiktechblog.com/javascript/destructuring-javascript-objects-and-deep-object-assignment/#respond Fri, 31 Jul 2020 02:14:28 +0000 https://karthiktechblog.com/?p=625 In this post, I will show you how destructuring JavaScript objects and deep assignment works in JavaScript. This is the continuation of my previous post Destructuring javascript array and its different usages. Destructuring JavaScript objects is very useful. I can use it for a deep object structure as well. In this example, I wanted to […]

The post Destructuring JavaScript objects and deep object assignment appeared first on KarthikTechBlog.

]]>
In this post, I will show you how destructuring JavaScript objects and deep assignment works in JavaScript. This is the continuation of my previous post Destructuring javascript array and its different usages.

Destructuring JavaScript objects and deep object assignment

Destructuring JavaScript objects is very useful. I can use it for a deep object structure as well.

In this example, I wanted to assign properties returned from an object to each individual variables.

var getPersonProfile = function() {
    return {
        firstName: "Karthik",
        lastName: "K",
        twitter: "KarthikTechBlog"
    }
}

var objectAssignmentExample = function() {
    let {
        firstName: firstName, 
        twitter: twitter
    } = getPersonProfile();

    console.log(firstName); // this produce "Karthik"
    console.log(twitter); // this produce "KarthikTechBlog"
}

This looks like I’m building an object but that is not the case. However, I’m building an object literal as the return value from the calling function is an object. Note that I have used curly brace “{“, “}” as it is an object.

Destructuring JavaScript objects

In other words, I’m telling JavaScript to assign firstName from the object returned from the getPersonProfile function. his way, firstName property in the objects are assigned to variable name firstName and similarly for twitter variable.

The right-hand side of the colon that is defining my variable. Properties that match the variable name will have the value assigned to it.

var getPersonProfileWithShortName = function() {
    return {
        first: "Karthik",
        lastName: "K",
        twit: "KarthikTechBlog"
    }
}

var objectAssignmentExample1 = function() {
    let {
        first: firstName, 
        twit: twitter
    } = getPersonProfileWithShortName();

    console.log(firstName); // this produce "Karthik"
    console.log(twitter); // this produce "KarthikTechBlog"
}

In this example, property name first matches and assigned value to firstName variable.

Deep Object Assignment

In this example, twitter property is inside social property. To access twitter property, you need to navigate to the social to get its value.

var getPersonProfile = function() {
    return {
        firstName: "Karthik",
        lastName: "K",
        social: {
            twitter: "KarthikTechBlog"
        }
    }
}

var objectAssignmentExample = function() {
    let {
        firstName: firstName, 
        social: {
            twitter : twitter 
        }
    } = getPersonProfile();

    console.log(firstName); // this produce "Karthik"
    console.log(twitter); // this produce "KarthikTechBlog"
}

Conclusion

In this post, I showed how destructuring JavaScript objects and deep object assignment works. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post Destructuring JavaScript objects and deep object assignment appeared first on KarthikTechBlog.

]]>
https://karthiktechblog.com/javascript/destructuring-javascript-objects-and-deep-object-assignment/feed/ 0 625
Destructuring javascript array and its different usages https://karthiktechblog.com/javascript/destructuring-javascript-array-and-its-different-usages/?utm_source=rss&utm_medium=rss&utm_campaign=destructuring-javascript-array-and-its-different-usages https://karthiktechblog.com/javascript/destructuring-javascript-array-and-its-different-usages/#respond Mon, 27 Jul 2020 20:35:48 +0000 https://karthiktechblog.com/?p=613 One of the new features in ES6 is the ability to destructing assignment. Destructing is an operation that you might have seen in other languages like Python or Ruby. Destructuring operation allows us to assign value to a set of variables by destructing it and doing pattern matching. A complex data structure like an array […]

The post Destructuring javascript array and its different usages appeared first on KarthikTechBlog.

]]>
One of the new features in ES6 is the ability to destructing assignment. Destructing is an operation that you might have seen in other languages like Python or Ruby.

Destructuring javascript array

Destructuring operation allows us to assign value to a set of variables by destructing it and doing pattern matching.

A complex data structure like an array or an object full of properties is a good example.

Let’s take an example. Two variables X and Y initialized with 2 and 3 values. In the third line we use destructing assignment to say give the value X and Y to Y and X. This will change the value of X to be 3 and Y to be 2 without using any other variable to swap its value.

Destructuring JavaScript Array

var destructingVariables = function () {
    let x = 2;
    let y = 3;
    [x, y] = [y, x];    
}

It is important to understand that what we see in the right hand side of this assignment is the array built with the values in Y and X.

To the left-hand side, it is not an array. It looks like I’m building an array literal. However, I’m working with individual variables X and Y and I’m surrounding them with square brackets. This is because I’m destructuring an array.

In simple form, I’m telling JavaScript to take the first item in the array and put it into X and the second one into Y.

var example1 = function () {
    let [x, y] = [2, 3];    
}

I can simplify this by mentioning let there be two variables X and Y.

var example2 = function () {
    let [x, y] = returnTwoNumbers();
}

var returnTwoNumbers = function() {
    return [2, 3];
}

I can even call an function and assign the values returned from it.

What if the function returns more than expected values? I can still use it by this way.

var returnThreeNumbers = function() {
    return [4, 2, 3];
}

var example3 = function () {
    let [, x, y] = returnThreeNumbers(); 
}

Output for all these examples are still same.

Destructuring JavaScript array and it's different usages
var returnThreeNumbers = function() {
    return [4, 2, 3];
}

var example3 = function () {
    let [, x, y, z] = returnThreeNumbers(); 
if(z===undefined) {
alert('z is undefined');
}
}

If I am trying to assign value to variable Z then Z will be undefined as there is no fourth value from the calling function.

Reference Post

Conclusion

In this post, I explained the destructuring javascript array and its different usages. I also showed how typescript shows the error upfront in visual studio code IDE. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post Destructuring javascript array and its different usages appeared first on KarthikTechBlog.

]]>
https://karthiktechblog.com/javascript/destructuring-javascript-array-and-its-different-usages/feed/ 0 613
Difference between var, let and const in JavaScript (ES6) https://karthiktechblog.com/javascript/difference-between-var-let-and-const-in-javascript/?utm_source=rss&utm_medium=rss&utm_campaign=difference-between-var-let-and-const-in-javascript https://karthiktechblog.com/javascript/difference-between-var-let-and-const-in-javascript/#respond Mon, 27 Jul 2020 19:09:40 +0000 https://karthiktechblog.com/?p=603 In this post, I will explain the difference between var, let, and const in Javascript. I will be using a visual studio code for the demo purpose. This module is part of variables and parameters which is part of JavaScript Fundamentals for ES6. These features are designed to make JavaScript code easier to read, write, […]

The post Difference between var, let and const in JavaScript (ES6) appeared first on KarthikTechBlog.

]]>
In this post, I will explain the difference between var, let, and const in Javascript.

Difference between var, let and const in JavaScript

I will be using a visual studio code for the demo purpose. This module is part of variables and parameters which is part of JavaScript Fundamentals for ES6.

These features are designed to make JavaScript code easier to read, write, and also to make this code safer. This will help avoid some dangerous behavior in javascript.

There are two new keywords that are used in declaring variables such as let, const, and also I will explain the difference with the var keyword.

var and let Keyword

let keyword allow us to define variable in JavaScript. var keyword can also be used to define variable. However, var keyword has some limitation when it comes to scope.

what is scope then? The scope of the variable is the area of the program where it is legal to use. var has only two scopes such as Global Scope and Function Scope. There is no block scope for var keyword.

scope explained for var keyword
// var Keyword scope example
var doSomeWork = function (raining) {
    if (raining) {
        var weather = '65F';
    }
    return weather;
};

let keyword solve this problem.

difference between var let and const in Javascript
// var Keyword scope example
var doSomeWork = function (raining) {
    if (raining) {
        var weather = '65F';
    }
    return weather;
};

// let Keyword scope example
var doSomeWork = function (raining) {
    if (raining) {
        let weather = '65F';
        return weather;
    }

    return '85F';
};

since variable “x” is available throughout the function there is no error. let the keyword makes the variable scoped to the condition and hence we got an error. Using such code through javascript runtime error stating no such variable exist.

All these confusion with the var keyword is because of the Hoisting. Hoisting is JavaScript’s default behavior of moving declarations to the top. You can read more here.

Another example is to use let keyword in for loops.

let keyword in for loop

const Keyword

The const keyword is another addition in ECMA Script 6 (ES6). The idea of using this is to create and initialize a read only variable. A variable that hold a constant value something that you never change.

ES6 for const will have block scoping.

var constFuntion = function () {
    const max_size = 20;
    max_size = 20 + 20; // syntax error as you cannot assign value again;
}
const keyword in ES6

Another difference with const and var keyword is you can define an variable more than once with var keyword. However, you cannot do the same with const keyword.

difference between var and const in Javascript

Conclusion

In this post, I showed the difference between var, let, and const in Javascript. I also showed how typescript shows the error upfront in visual studio code IDE. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post Difference between var, let and const in JavaScript (ES6) appeared first on KarthikTechBlog.

]]>
https://karthiktechblog.com/javascript/difference-between-var-let-and-const-in-javascript/feed/ 0 603