Felix Kling

Felix Kling

1571728453

The Complete Guide to Javascript Variables

What is a variable?

First things first, let’s get a good definition.

A variable is a named location for storing a value. That way an unpredictable value can be accessed through a predetermined name. — MDN

Think of it as a placeholder.

When you say to yourself, “I need to remember all this information later, but I only want to remember one word”…that’s a variable!

Types

JS is a dynamically typed language, so we generally don’t have to worry about assigning the type of data that is being stored in that variable. However, knowing the types makes debugging a lot easier.

Variables don’t have types, but the values in them do. These types define intrinsic behavior of the values. — Kyle Simpson

JavaScript defines seven built-in types:

Note: All of these types except object are called “primitives”.

In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods. — MDN

null

Represents the intentional absence of any object value — MDN

null is something you (the human) use to purposefully say, this variable has no value.

General Usage

Consistent way of returning from a function that doesn’t yield results:

function return3 (value) {
        if(value === 3) { return value }
        else { return null }
    }    return3(2) // null

If we didn’t tell it to return null, it would return undefined.

undefined

Defines a variable that does not have a value. In other words, the JS Engine is aware that a variable exists, but it has no value. This may seem similar to null but they are different. The main difference is that null is a defined value, whereas undefined is not. For a great article about this specific topic, check this out.

let b;
console.log(b) // undefined

boolean

Simple true or false

let falseVariable = false

number

The number in JS differs from other programming languages that define what type of number, e.g. float, integer, etc. Instead, JS uses the double-precision 64-bit floating point format (IEEE 754). That means you don’t have to worry about the type of number when declaring it. Just declare away!

let four = 4;
let fiveish = 5.1;
console.log(four + fiveish) // 9.1

General Usage

A value you expect to do something computational with, e.g. math.

string

A sequence of characters. For example, this sentence.

let someString = "I'm a string!"

General Usage

Storing information to display to the user.

object

An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). — MDN

let car = {
        color: "red",
        miles: 400,
    }console.log(car.color) //red

General Usage

Everything. Which, is only partially a joke. I use JS objects to pass data around in an application.

A note about the Array

Technically speaking, an Array is an object. If you don’t believe me run this in the console:

typeof [1,2,3] === "object";

However, as Kyle Simpson notes:

It’s most appropriate to think of them (arrays) also as a “subtype” of object (see Chapter 3), in this case with the additional characteristics of being numerically indexed (as opposed to just being string-keyed like plain objects) and maintaining an automatically updated .length property.

symbol — added in ES6!

Unique Identifiers. No two symbols will ever be the same. Useful as object keys, in large data structures.

Avoid Naming collisions

Gotta be honest, I haven’t used this in the real world, so maybe someone has a good example to share! However, I found a really good overview of symbols here.

Bonus!

undeclared

Undeclared means that the variable you are trying to access is not available in the scope, which we’ll talk about in length in a minute. The error you will see is ReferenceError: x is not defined .

Declaring variables

There are three different ways to declare a variable in Javascript. We’re going to talk about all three: var , let and const .

var vs const vs let

It’s been a minute since const and let were standardized into the JS Spec (2295360 as of the minute I’m writing this).

var

Old school way of defining a variable in JS. It was king of the block for a long time, until it’s much more specific brothers came long.

  • can be changed
  • scoped globally or locally to an entire function regardless of block scope.

let

  • can be changed.
  • scoped to the block.
  • let variables are not initialized until their definition is evaluated. — MDN

const

  • cannot be changed after instantiation.
  • scoped to the block.

when to use let vs const

There are two camps about how to approach when to use what.

  1. I don’t trust anyone

This method says, use const first for every variable. If the need comes along that you need to change a variable after it’s been declared, change it to let.

  1. I trust myself

This method says, use let for everything. If the need comes along that you need to make sure a variable can’t be changed, change it to const.

Moral of the story here:

  • Don’t use var anymore. If you’re worried about compatibility in browsers, it has 94% global compatibility. If that still isn’t good enough (there are some edge cases), you probably should use Babel to poly-fill other things anyways.

Coercion

What if I told you that you could change the past.

Check it out.

let threeString = "3";
let threeNum = 3;

They look different right? One is obviously a number and one obviously a string .

If we do this, you’d expect it to throw an error:

let sum = threeString + threeNum

But it doesn’t! JS “coerces” threeString into a number so it can do math. Thanks JS…I think? In this scenario, it’s probably fine. However, you can run into issues if you are trying to evalute an expressions “truthy-ness”. Check out this article for an even DEEPER dive.

Scope

Scope in Javascript refers to:

The current context of execution. — MDN

This means different things depending on whether we are talking about the old school var or the new school const / let . Scope comes in two flavors: local and global.

Global

Global scope is anything at the top level of the file.

var globalVar = "I'm global!"
    let globalLet = "I'm also global!"
    const globalConst = "I'm global too!"    function someFunction() {
        console.log(globalVar); // I'm global!
        console.log(globalLet); // I'm also global!
        console.log(globalConst); // I'm global too!
    }

Local

The definition of local scope changes slightly, depending on whether you are talking about var or let/const.

var (functional scope)

A var statement when called within a function, is available anywhere in that function. For example:

function someFunction() {
        if(true) {
            var localScope = "Yo! Call me!"
            console.log(localScope) // "Yo! Call me!"      
        }
        console.log(localScope) // "Yo! Call me!"
    }

As long as it’s within that function, it’s available to be called.

let and const (block scope)

The new kids on the block let and const are BLOCK scoped, which means they are only available within the block they are in.

Examples of blocks are: if/switch statements, for/while loops. Or, as described expertly in this article:

Generally speaking, whenever you see {curly brackets}, it is a block.

Using the same example:

function someFunction() {
        if(true) {
            let localScope = "Yo! Call me!"
            console.log(localScope) // "Yo! Call me!"      
        }
        console.log(localScope) // Uncaught ReferenceError: localScope is not defined
    }

Hoisting

Per the MDN docs:

Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it’s declared. This behavior is called “hoisting”, as it appears that the variable declaration is moved to the top of the function or global code.

More simply put:

all declarations, both variables and functions, are processed first, before any part of your code is executed. — Kyle Simpson

When a var statement is hoisted to the top of the context, it is assigned a value of undefined .

hoistedVar = "I've been hoisted!";
var hoistedVar;console.log(hoistedVar) // I've been hoisted!

What better way to understand it than using Tyler McGinnis’ amazing Javascript Visualizer! As you can see, both variables are given a value of undefined as soon the Creation phase starts. This allows the compiler to assign the value of “I’ve been Hoisted” to the value when it parses through the code during execution.

Let and Const Caveat

let and const are not hoisted in the same way that var is. var is initialized as undefined when they are hoisted. let and const remain uninitialized until the statement is evaluated by the compiler. Thanks, Bergi, for the insight.

Therefore, using the same example:

hoistedVar = "I've been hoisted!";
    let hoistedVar;    console.log(hoistedVar) // Uncaught ReferenceError: 
                                                    //Cannot access 'hoistedVar' before initialization

Style Choices

Casing

When you declare variables, there’s a bunch of different options. The style is up to you, but just keep it consistent.

Camel Casing (Dromedary)

let camelCasedVar = "Im camel cased"

This is used for common variables throughout my applications.

Camel Casing (Pascal)

let PascalCasedVar = "Im Pascal cased"

I use Pascal casing for Classes or Components.

Snake Case

let snake_case_var = "Sssssnake case"

This method is pretty common in PhP, for whatever reason, but I haven’t seen it much in JS land. I don’t really like it anyways, so I don’t use it anymore.

Kebab-case

<input id="kebab-case-input">

According to StackOverflow, this convention is known colloquially as kebab-case. While this method can’t be used by JS, it is a common convention in HTML. I try to avoid it for reasons mentioned below.

What I use

I typically use camel casing, for everything (CSS, JS, HTML). For one, it seems to be pretty standard about the JS world, but also because it makes writing out selectors a little cleaner/consistent.

Consider the example below:

<form action="/" id="form">
      <input type="text" id="kebab-case">
      <input type="text" id="camelCase">
      <button type="submit">Submit</button>
    </form>// When we submit form data, we can access it via the event parameter.  
    let form = document.getElementById("form")
    form.addEventListener("submit", function(event) {
        event.preventDefault();            // if we use hyphens, we have to use brackets/quotes to get the value
        const kebabInput = event.target["kebab-case"].value            // if we use anything without special characters, we can use dot notation
        const camelInput = e.target.camelCase.value
    }, false)

I think this makes for cleaner code, but I’ll leave that up to you to debate.

What do I call this variable?

Now that you know where you’re going to be able to access it, and whether you can change it or not, it’s time to name it! If you’re like me, it takes a good five minutes to settle on a variable name. Over the years, I’ve come across some helpful tips to avoid that wasted time. The most important one:

Name it what it is.

Wow, what great advice.
I know it sounds simple, but just think about what exact information is going to be held in this variable and what you’re going to do with it. Try to avoid using single character variables like i, e or p. Use whole words. If your text editor is any good, it’ll autocomplete those for you anyways.

Reserved Words

Just a note, there are a bunch of reserved words in JS. For instance: abstract, var and boolean. You can check them all out here.

Final Thoughts

Wow, we made it to the end. Congratulations! Honestly, there is a lot of information here. We talked all about types, hoisting, coercion, and threw in some ES6 for flavor. There’s no way we covered it all.

Did I miss anything? What other topics should we explore together?

Leave a comment below!

As always, happy coding!

#javascript

What is GEEK

Buddha Community

The Complete Guide to Javascript Variables

Rahul Jangid

1622207074

What is JavaScript - Stackfindover - Blog

Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.

Who invented JavaScript?

JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.

What is JavaScript?

JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.

Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.

JavaScript Hello World Program

In JavaScript, ‘document.write‘ is used to represent a string on a browser.

<script type="text/javascript">
	document.write("Hello World!");
</script>

How to comment JavaScript code?

  • For single line comment in JavaScript we have to use // (double slashes)
  • For multiple line comments we have to use / * – – * /
<script type="text/javascript">

//single line comment

/* document.write("Hello"); */

</script>

Advantages and Disadvantages of JavaScript

#javascript #javascript code #javascript hello world #what is javascript #who invented javascript

Hire Dedicated JavaScript Developers -Hire JavaScript Developers

It is said that a digital resource a business has must be interactive in nature, so the website or the business app should be interactive. How do you make the app interactive? With the use of JavaScript.

Does your business need an interactive website or app?

Hire Dedicated JavaScript Developer from WebClues Infotech as the developer we offer is highly skilled and expert in what they do. Our developers are collaborative in nature and work with complete transparency with the customers.

The technology used to develop the overall app by the developers from WebClues Infotech is at par with the latest available technology.

Get your business app with JavaScript

For more inquiry click here https://bit.ly/31eZyDZ

Book Free Interview: https://bit.ly/3dDShFg

#hire dedicated javascript developers #hire javascript developers #top javascript developers for hire #hire javascript developer #hire a freelancer for javascript developer #hire the best javascript developers

Niraj Kafle

1589255577

The essential JavaScript concepts that you should understand

As a JavaScript developer of any level, you need to understand its foundational concepts and some of the new ideas that help us developing code. In this article, we are going to review 16 basic concepts. So without further ado, let’s get to it.

#javascript-interview #javascript-development #javascript-fundamental #javascript #javascript-tips

Cayla  Erdman

Cayla Erdman

1597470780

A quick guide to JavaScript Arrays

Introduction

Arrays are a structure common to all programming languages so knowing what they are and having a firm grasp on what you’re able to accomplish with Arrays will take you a long way in your journey as a software developer. The code examples I share in this post will be in JavaScript but the concepts are common among all languages. What you learn here can easily be translated to any other language you work with.

In this post I’ll be covering how to perform the create, read update and delete operations using arrays, some common functions that come with the Array prototype and also how to implement them.


What is an Array

Before we jump into the juicy bits of Arrays, lets quickly gloss over what they are. Arrays

  • are a fundamental data type in JavaScript
  • are an ordered collection of values called **elements **that are stored at and accessed via an index
  • are untyped, meaning that the elements of an array could be of different types. This allows us to create complex arrays such as an array of objects or even an array of arrays (multidimensional arrays)
  • can have elements that are constants or expressions
  • have a property called length that tells you the number of elements in the array
  • inherit properties from Array.prototype that includes a wide variety useful functions that can be called from arrays or array-like objects

CRUD operations using Arrays

If you’re not familiar with the term CRUD it stands for Create, Read, Update and Delete. In this section we’ll go through each one of these operations and cover different ways you can perform each one.

Creating Arrays

There are several ways you can create an Array but the most common ways are by using

  • the Array literal syntax
  • the Array constructor i.e. new Array()

Lets take a look at each one with examples

Array literal

The array literal is the most common way of creating an array. It uses the square brackets as a notion of a container followed by comma separated values inside the square brackets. The following examples show how to use the array literal syntax and how arrays are untyped i.e. can contain elements of different types.

Image for post

Examples of untyped arrays in JavaScript created with the array literal syntax.

Array constructor

Another way to create an array is through the Array constructor.

const myArray = new Array();

Using the Array constructor, as shown above, is the same as creating an array with the array literal syntax. i.e.

// The following two lines behave exactly the same way i.e. both create an empty arrays

const myArray = new Array();
const myOtherArray = [];

The array constructor, however, is able to receive arguments that allow it to behave in different ways depending on the number and type of arguments passed to it.

  • You can pass a single numeric argument which creates an array of the specified length. This option is mostly used when you know how many elements you’ll be placing in the array
const myArray = new Array(5);

Note: If you want to define the array with a specified size, as shown above, the argument passed must be a numeric value. Any other type would be considered as the first element that’ll be placed in the array.

  • Or you can pass two or more arguments or a non-numeric argument to place the values inside the array. This works the same way as shown in the array literal examples.

Image for post

Examples of arrays created by using the Array constructor in JavaScript

As stated earlier, these two ways are the most common ways of creating arrays that you’ll see and use 99% of the time. There are a few other ways but we won’t dive deep into how they work. They are

  • the spread operator const someArray = […someOtherArray]
  • the static method Array.of()
  • and the static method Array.from()

#javascript #web-development #javascript-tips #javascript-development #javascript-arrays #sql

Ajay Kapoor

1626321063

JS Development Company India | JavaScript Development Services

PixelCrayons: Our JavaScript web development service offers you a feature-packed & dynamic web application that effectively caters to your business challenges and provide you the best RoI. Our JavaScript web development company works on all major frameworks & libraries like Angular, React, Nodejs, Vue.js, to name a few.

With 15+ years of domain expertise, we have successfully delivered 13800+ projects and have successfully garnered 6800+ happy customers with 97%+ client retention rate.

Looking for professional JavaScript web app development services? We provide custom JavaScript development services applying latest version frameworks and libraries to propel businesses to the next level. Our well-defined and manageable JS development processes are balanced between cost, time and quality along with clear communication.

Our JavaScript development companies offers you strict NDA, 100% money back guarantee and agile/DevOps approach.

#javascript development company #javascript development services #javascript web development #javascript development #javascript web development services #javascript web development company