Categories
JavaScript Basics

Highlights of JavaScript — Alerts, Variables, Numbers, and Strings

To learn JavaScript, we must learn the basics.

In this article, we’ll look at the most basic parts of the JavaScript language.

Alerts

The alert function displays an alert box with some text we pass in.

The text comes from the string argument.

For instance, can write:

alert("hello world!");

and ‘hello world’ would be displayed.

It is a global function, so it’s a property of window . window.alert is the same as alert .

The short form is fine for inclusion in our code.

Variables and Strings

Strings are basic elements of JavaScript code. They store text data.

A variable with the given name can only be declared once.

They can be stored in variables. Variables are names that we choose and assign values to so that we can store them for use later.

For example, we can write:

let name = "james";

to store names.

We can set a variable declared with let to a new value.

For example, we can write:

let name = "james";
name = "mark";

Then the value of name will be "mark" .

We can declare a variable and leave it undefined.

For instance, we can write:

let name;
name = "james";

We can do this with variables declared with let .

Variables can be declared with any name that isn’t in the reserved keywords list.

The list is at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords.

Variables aren’t enclosed in quotes and text strings are enclosed in quotes.

JavaScript strings can be enclosed in single or double-quotes.

They can also be enclosed with backticks.

If they’re enclosed with backticks, then they have to have variables embedded in them.

For example, we can write:

let firstName = 'james';
let lastName = 'smith';
let name = `${firstName} ${lastName}`;

We interpolate the value of firstName and lastName into the string. So name should be 'james smith' .

This is a template literal. We can put any expression inside the strings.

This is a very convenient way to combine various expressions into a string.

Now we can assign variables, we can pass variables into alert instead of passing the whole string.

For example, we can write:

let text = "hello world!"
alert(text);

We pass in text into alert as an argument to display the alert.

We can reference text anywhere after it’s defined.

Variables and Numbers

Numbers are another primitive data type with JavaScript.

We can also assign them to variables.

For example, we can write:

let length = 100;

This makes doing operations on it easy. For example, we can add a number to length :

length + 10

then the sum of length and 10 is 110.

We know that length isn’t a variable because it’s not enclosed in quotes.

And numbers alone can be used variable names, so JavaScript knows it’s a number.

We can replace 10 with a variable by assigning it to a variable.

For example, we can write:

let length = 100;
let additionalLength = 10;
let totalLength = length + additionaLength;

We have the additionalLength variable that we add to the length and assign the sum to the totalLength variable.

Conclusion

We can create variables to store numbers and strings and use them with alerts.

Categories
JavaScript Basics

Highlights of JavaScript — Variables and Math Expressions

To learn JavaScript, we must learn the basics.

In this article, we’ll look at the most basic parts of the JavaScript language.

Variable Naming

We can’t have variable names that start with a number, but we can have variables that have numbers in the middle.

For example, we can write:

let name1 = "james";

but not:

let 1name = "james";

There are more rules to JavaScript variable naming.

A variable name can’t have any spaces.

Variable names can only have letters, numbers, dollar signs and underscores.

Variable names can’t be a reserved JavaScript keyword, but they can contain them.

Capital letters can be used, but we must be aware that variable names are case sensitive.

So name isn’t the same as Name .

JavaScript variable names are usually camelCase. They let us form variables with multiple words and we can read them all easily.

So we can write variable names like firstName to make the 2 words in the variable name clear.

Math Expressions

Most JavaScript programs will do math. Therefore, JavaScript comes with operators for various common math operations.

For example, we can add with the + operator:

let num = 2 + 2;

To subtract, we can use the - operator:

let num = 2 - 2;

Multiplication is done with the * operator:

let num = 2 * 2;

And division is done with the / operator:

let num = 2 / 2;

There’s also the % modulus operator to find the remainder of the left operand divided by the right one.

For example, we can write:

let num = 2 % 2;

We get 0 because 2 is evenly divisible by itself.

The exponentiation operator is denoted by ** . For example, we can use it by writing:

let num =  2 ** 2;

Then we raise 2 to the 2nd power.

The ++ operator adds the variable’s value by 1 and assign it to the variable.

For example:

num++;

is the same as:

num = num + 1;

We can use the expressions with the assignment operator, but we may get results that we don’t expect.

For example, if we have:

let num = 1;
let newNum = num++;

Then newNum is 1 since the original value of num is returned.

On the other hand, if we have:

let num = 1;
let newNum = ++num;

Then newNum is 1 since the latest value of num is returned if ++ is before the num .

Likewise, JavaScript has the -- operator to subtract a variable by 1 and assign the latest value to the variable.

For example, we can write:

let num = 1;
let newNum = num--;

And we get 1 for newNum and:

let num = 1;
let newNum = --num;

then we get 0 for newNum .

How the values are returned work the same way as ++ .

Conclusion

We have to name JavaScript variables by following its rules.

Also, JavaScript comes with many operators for doing math operations.

Categories
JavaScript Basics

Highlights of JavaScript — Math Expressions and Prompts

To learn JavaScript, we must learn the basics.

In this article, we’ll look at the most basic parts of the JavaScript language.

Math Expressions

We should eliminate ambiguity with JavaScript math expressions.

For example, if we have:

let totalCost = 1 + 3 * 10;

then readers may be confused about which operation comes first.

JavaScript has precedence rules for operators. They generally follow the same rules as normal math.

However, we can make everyone’s lives easier by wrapping parentheses around expressions that have higher precedence.

For example, we can write:

let totalCost = 1 + (3 * 10);

then we wrap the expressions around the multiplication.

Now we know the multiplication operation comes first.

If we move the parentheses, then the operations would be done in a different order.

For instance, if we have:

let totalCost = (1 + 3) * 10;

then the addition is done before the multiplication.

Concatenating Strings

Strings are text values and they can be combined with concatenation.

For example, we can write:

alert("Thanks, " + userName + "!");

to combine the 3 expressions into 1 with the + operator.

If userName is 'james' , then we have:

'Thanks, james!'

The 3 parts are combined together and returned as one string.

We can concatenate strings with any other JavaScript expressions.

They’ll be converted to strings automatically so that they can be concatenated together.

So if we have:

alert("2 plus 3 equals " + 2 + 3);

Then we get '2 plus 3 equals 23' .

This is because 2 and 3 are converted to strings before they’re concatenated.

A more convenient way to combine strings and other expressions is to use template literals.

For example, we can write:

alert(`2 plus 3 equals ${2 + 3}`);

We replaced the quotes with the backticks.

Then we use the ${} symbols to surround the JavaScripot expressions to interpolate the expressions.

This way, we have 2 + 3 returning a number since they’re concatenated with strings.

So we get '2 plus 3 equals 5' .

Prompts

A prompt box lets us ask use for some information and provide a response field for the answer.

For example, we can write:

let name = prompt("Your name?", "mary");

We call prompt with the question string as the first argument.

The 2nd argument is the default answer returned.

If we call that, the browser will show an alert box with an input box to let us enter our answer.

Then when we click OK, then the response is returned if it’s entered.

Otherwise, the default answer is returned.

If we omit the default answer in the 2nd argument and we entered nothing, then it returned null .

prompt is a global function, so window.prompt is the same as prompt .

But we can just write prompt .

Conclusion

We can take text answers from a user with the prompt function.

Math expressions can be made clearer with parentheses.

Categories
JavaScript Basics

Spreading Arrays with JavaScript

The spread operator is one of the best recent JavaScript features.

In this article, we’ll look at what we can do with the spread operator.

Spread Operator

Rhe spread syntax lets us expand iterable objects like arrays and strings in various situations.

Merging Arrays

We can merge arrays with it.

For example, we can write:

const a = [1, 2, 3];
const b = [4, 5, 6];
const c = [...a, ...b];

We put all the items from a and b into a new array and assign it to c .

So c is:

[1, 2, 3, 4, 5, 6]

Clone Array

Another way we can use it is to shallow copy an array.

For example, we can write:

const arr = [1, 2, 3];
const arrCopy = [...arr];

We made a copy with the spread operator. It expands the arr entries into a new array.

So arrCopy is also [1, 2, 3] .

But they reference different objects in memory.

Arguments to Array

The arguments object is an iterable object that has the arguments passed into a JavaScript function.

It’s only available in a traditional function.

For instance, we can write:

function foo() {
  const args = [...arguments];
  console.log(args);
}

args is an array.

So if we have:

foo(1, 2, 3)

Then args is [1, 2, 3] .

A more modern alternative that works with all functions is the rest operator:

const foo = (...args) => {
  console.log(args);
}

Then if we call it the same way:

foo(1, 2, 3)

args would have the same value.

String to Array

We can convert a string into an array of characters with the spread operator since string are iterable.

For example, we can write:

const string = 'hello world';
const array = [...string];

Then array is:

["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]

Set to Array

A set is an iterable object that can’t have duplicate entries.

Since it’s iterable, we can use the spread operator with it.

For example, we can write:

const set = new Set([1, 2, 2, 3, 3]);
const arr = [...set];

Then arr is [1, 2, 3] since the duplicates are removed from the set.

Map to Array

Maps are key-value pairs that’s stored in an object.

It’s also iterable so we can use the spread operator with it.

For example, we can write:

const map = new Map([
  ['foo', 1],
  ['bar', 2]
]);
const arr = [...map];

We spread the map with the operator and arr would be:

[
  ['foo', 1],
  ['bar', 2]
]

Node List to Array

Node lists are a list of DOM nodes.

It’s an iterable object but it’s not an array.

To convert them to an array, we can write:

const nodeList = document.querySelectorAll('div');
const nodeArr = [...nodeList];

We convert the node list returned from querySelectorAll to an array with the spread operator.

Conclusion

We can use the spread operator to spread or copy arrays and convert iterable objects to arrays.

Categories
JavaScript Basics

How to Append Items to a JavaScript Array?

There are a few ways to append items to an array in JavaScript.

In this article, we’ll look at how to do that in different ways.

Array.prototype.push

The push method appends one more item into an array.

We can use it by writing:

arr.push('foo');

to add 'foo' to arr .

Also, we can add multiple elements to an array with it:”

arr.push('foo', 'bar');

Then both 'foo' and 'bar' are added to arr in the same order.

This also means we can use the spread operator to append then entries of an array with push :

arr.push(...['foo', 'bar']);

That does the same thing as the previous example.

Spread Operator

We can use the spread operator to create a new array with new entries added to it.

For instance, we can write:

arr = [...arr, 'foo', 'bar'];

We used the spread operator to spread the existing entries of arr into a new array.

Then we added 'foo' and 'bar' to it at the end.

Then we assigned the new array back to arr .

Array.prototype.splice

Also, we can use the splice method fo the array instance to append to an array.

It takes 3 or more arguments, which are the start index, deletes count, and items, we want to add.

To add items into an array, we can write:

arr.splice(arr.length, 0. 'foo', 'bar');

In the code above, we indicated that we want to start at the last index of the array + 1 with arr.length .

0 means we remove nothing.

The 'foo' and 'bar' are the items we add.

Set an Item to the length Index

JavaScript arrays aren’t fixed length, so we can assign an entry to any index.

If we want to append an entry to an array, then we can set it using the bracket notation as follows:

arr[arr.length] = 'foo';

Then we can append 'foo' to arr since arr.length is one index beyond the end index of the original array.

Array.prototype.concat

We can use the concat method of the array instance to append one or more entries into the array.

For instance, we can write:

arr = arr.concat('foo', 'bar');

Also, we can write:

arr = arr.concat(...['foo', 'bar']);

Either way, we pass in one or more arguments for the items we want to append to the new array in addition to the existing ones.

concat returns a new array, so we’ve to assign it to a variable to access it.

Mutate or Not

It’s better that we don’t mutate the array so that we keep the existing value.

It’s easier to test and track immutable data.

Therefore, it’s preferred to not mutate data if possible.

Conclusion

In JavaScript, there are many ways to append an item to an array.

We can use the spread operator, or we can use various array methods to do the same thing.

Some operators or methods mutate and some don’t, so we’ve to be careful when using them.