Learning JavaScript

JavaScript Data Types, Values, and Variables

Bitesize JavaScript is a series of short lessons covering fundamental coding concepts. The goal is to quickly introduce you to the language and provide you with enough information to begin exploring the concepts in more depth. Each lesson is designed take a short amount of time to digest new topics and then apply them through example.

  1. JavaScript Data Types, Values, and Variables
  2. JavaScript Operators
  3. JavaScript Conditional Statements
  4. JavaScript Loops
  5. JavaScript Functions
  6. JavaScript Call Stack
  7. JavaScript Scope
  8. JavaScript Arrays – Fundamentals
  9. JavaScript Arrays – Properties and Methods
  10. JavaScript Objects
  11. JavaScript Manipulating the Document Object Model (DOM)

JavaScript is one of the three core technologies used to build websites and web applications. Alongside HTML and CSS , JavaScript provides the interactive functionality commonly used throughout the web. In this lesson you will be introduced to some of the core concepts of JavaScript .

To follow along, you will need a modern web browser , such as Google Chrome or equivalent with developer tools. You will also need a capable text editor. I highly recommend Microsoft Visual Studio Code. The first concept we are going to cover in this lesson is variables . Variables are spaces of memory where you can store information of a certain type, that can be retrieved later in your code.

JavaScript is capable of storing five different types of primitive data types within variables . These include:

  • Number (including whole, integer, float)
  • String (or text)
  • Boolean
  • Undefined (a variable that has not yet been assigned a value or type)
  • Null (an assignment representing no value)

The keyword let is used to declare a variable . A variable can either be declared as undefined (without a value set) or defined with a value . The following examples illustrate declaring variables of different types.

let studentName = 'Fred Jones'; // string. Strings are always stored in quotes let gpa = 3.6; // number. Numbers are stored without quotes let graduated = false; // boolean. Either true or false can be assigned let quizResult; // undefined

Note each statement in JavaScript ends with a semi-colon. The // is used to create an in- line comment , i.e. anything written after // will be ignored. You can also write multi-line comments by enclosing your comments in /* and */.

Variable names have certain rules that we need to follow. All variable names must start with an underscore _ or letter. The rest of the name can contain any letter, any number, or the underscore. You can’t use any other characters. Variables are case-sensitive.

Now that you have learned the basics of variables , let’s try using some next.

→ Try it out in the Browser Console

In Chrome (or an equivalent browser ), open the development tools. Using Chrome you can access ‘developer’ tools in the view menu (Mac) or tools menu (Windows). Alternatively, right-clicking an empty area in the browser window and selecting ‘inspect’ will also get you there. You can also open the console by pressing Ctrl+Shift+J (Windows / Linux) or Cmd+Opt+J (Mac).

Next try declaring the studentName variable as above. Once you hit enter on the keyboard, enter the command :

Читайте также:  Sass to css конвертер

You should now see the relevant output showing the value of studentName as shown in the screenshot below.

console

The console.log command is a very handy way of quickly outputting results to the console. As shown above, we have successfully declared the studentName variable and assigned the value ‘Fred Jones’. Strings are always stored using either single or double quotes. The console.log command confirms our value is stored to the variable .

→ Try it out in Code Files

While the developer tools are very handy for quick debugging , you typically will write JavaScript code within text files. As mentioned above, I highly recommend Visual Studio Code for editing purposes, and this is the editor I use throughout this course. To get started, create a new project folder on your computer called bite-size-javascript and open VS Code (or an equivalent editor ) and create two new files in this directory called index.html and script.js.

     

Learning JavaScript

/** * Variables and Types */ let studentName = 'Fred Jones'; // string. Strings are always stored in quotes console.log(studentName) let gpa = 3.6; // number. Numbers are stored without quotes console.log(gpa) let graduated = false; // boolean. Either true or false can be assigned console.log(graduated) let quizResult; // undefined console.log(quizResult) let emptyValue = null; // null console.log(emptyValue)

Earlier, you were introduced to single line comments. Note the top line beginning with /* This is called a multi- line comment . Multiline comments can appear anywhere between an opening /* and closing */ In this case we are using a multi- line comment to include a human-readable header for our code called ‘ Variables and Types’. Comments make our code easier to read and will make more sense to you as you get practice using them.

Open index.html in your browser and open the console, Press Ctrl+Shift+J (Windows / Linux) or Cmd+Opt+J (Mac).

You should see results similar to the screenshot below.

vscode

Note each of the different variables display their associated value in the console.

Coercion and Mutation

So far you have learned about variables and the types of data that can be stored within them. The data types (string, number, boolean, etc.) are tied to the value in JavaScript , and not the variable container itself. For example, if I have a variable called gpa and store 3.6 (number) as the value , I can later coerce this into a string by combining (or concatenating) it with other variables . If I combine studentName and gpa by using the + function in JavaScript , the resulting output will be provided in a string.

Other languages, such as Java and C# enforce strict typing, meaning the variable itself (in this case student) would be assigned a type of string. If I later tried to store the boolean true value, I would receive a compilation error.

Similarly, because JavaScript does not enforce the data type at the variable , different values of different data types can be stored over time. Just like coercion, which happens when variables are coerced into a different type, mutation can occur when a different value of a different type is stored in the variable . Take the gpa variable from the example above. In the code it is a value set to 3.6 (number). We can however update this variable and store a value of “three point six” (string). Both coercion and mutation are made possible by using JavaScript ‘s dynamic typing. To summarize, JavaScript will allow you to store values of any type within a variable without enforcement. Let’s look at a couple of examples to better understand this process.

Читайте также:  Css оформление блогов 2021

In your script.js file , update the code, adding the new lines on the end starting with the comments ‘Coercion and Mutation’:

/** * Variables and Types */ let studentName = 'Fred Jones'; // string. Strings are always stored in quotes console.log(studentName) let gpa = 3.6; // number. Numbers are stored without quotes console.log(gpa) let graduated = false; // boolean. Either true or false can be assigned console.log(graduated) let quizResult; // undefined console.log(quizResult) let emptyValue = null; // null console.log(emptyValue) /** * Coercion and Mutation */ // Type Coercion Example console.log(studentName + ' ' + gpa) // The + concatenates studentName with an empty space and gpa is coerced into a string // Variable Mutation Example gpa = "three point six"; // JavaScript changes the data type to string and updates the gpa variable console.log(gpa)

You should now feel comfortable with the JavaScript fundamental programming concept of data types, variables , and dynamic typing.

Источник

Types, values, and variables in JavaScript

These will be the values used by the computer program.
First is a set of characters and the second is digit/number these are called types.

Ok, what if we want these values later in our program?
Let’s save values in some container and name that container as abc.
This container is called a variable.

JavaScript types mainly can be divided into two categories:-

Primitive types include numbers, strings of text, and boolean values(true/false).
The special type of values like null and undefined are primitive values, but they are not numbers, strings, or boolean.
ES6 added a new special-purpose type, known as Symbol.

Any value that is not a primitive value(number, string, boolean, symbol, null, or undefined) is an Object.

An object is a collection of properties where each property has a name and value pair.
The values of an object can be a primitive value or another object.

JavaScript automatically converts values from one type to another. If the program expects a string and you provided a number, it will automatically convert the number to a string.

Numbers

The number is used to represent integers.
JavaScript represents numbers using a 64-bit floating-point format defined by IEEE 754 standard.

This means it can represent numbers as large as +/- 1.7976931348623157*10^308 and as small as +/- 5*10^-324.

If we use integer values larger than the range, we may lose precision in trailing digits.

If a number appears directly in a JavaScript program it is called numeric literals.
I will explain Numbers in detail in an upcoming article.

Text

To represent text in our program JavaScript provides type as a String.

A String is an immutable ordered sequence of 16-bit values. Each 16-bit value represents a Unicode character.

The length is the number of 16-bit values that are used to represent a string.
JavaScript strings use zero-based indexing, the first 16-bit value is placed at 0th index and 2nd at 1st index, and so on.

Читайте также:  Java net socketexception android permission denied

You can find details about strings in javascript in upcoming articles.

Boolean values

null is a reserved keyword to represent the absence of the value.

Using typeof operator on null returns type as an “object”, indicating that null can be used as a special value that indicates “no object”.

Other programming languages also have equivalent Javascript null: like NULL, nil, or None.

The undefined value represents a deeper kind of absence. It is the value of the variable that not has been initialized.

Many times we see this value when we try to get the value of an object property or array element which does not exist.

undefined is a predefined global constant(not language keyword as null) that is initialized to an undefined value.

If we try to apply typeof operator to an undefined value it returns “undefined”, indicating that this is a member of a special type.

Symbols

Symbols were introduced in ES6 to use non-string property names.

JavaScript Object types are an unordered collection of properties, where each property has a name and value.

Before ES6 property names are typically a string.

To obtain symbol values, we need to call the Symbol() function.
This function never returns the same value twice even we call it with the same argument.

Symbol.for()-
This method allows us to create the same symbol value twice.
Passing the same string argument to Symbol.for() method returns the same symbol value.
Symbol.keyFor() returns the string that we passed as an argument to Symbol.for().

let var1 = Symbol.for(“test”); let var2 = Symbol.for(“test”); va1 === var2 // true 

Variable Declaration and Assignment

In the programming language, we use names/identifiers to represent values.

Binding name to value gives us a way to refer to that value ad use it in the programs we write.

By doing this we can say that we are assigning value to a variable.

The term variable implies that a new value can be assigned: the value associated with the variable may vary as our program runs.

If we permanently assign some value to a name, that name we refer to as constant instead of variable.

Variable and scope

The scope of a variable is the region of our program source code in which it is defined.

Variable and constant declared with let and const are blocked scope. This means the variable is only accessible inside the code block where let or const exists.

var as a global variable

If we declare the global variable using the var keyword it is a part of the global object and can be referred to as globalThis.

Global declared with var can not be deleted using the delete keyword.

Variable declared with let and const are not a part of globalThis.

This is an overview of Javascript types and variables.

In the next article from this series, I will cover the Number data type in detail.

Hope you like it, if yes **like & share.**

Thanks for your time.

Happy coding….

Источник

Оцените статью