Categories
JavaScript Basics

Highlights of JavaScript — Find Characters and Convert Between 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.

Finding a Character at a Location in a String

We can find a character at a location in a string with the charAt method or the square brackets notation.

For example, we can write:

let firstChar = 'james'.charAt(0)

then firstChar is 'j' .

This is the same as:

let firstChar = 'james'[0]

They’re the same, so the square brackets are used more often since it’s shorter.

Replacing Characters

The replace method lets us replace characters.

For example, we can write:

let newText = text.replace("World War II", "the Second World War");

to replace “World War II” with the “the Second World War” .

It’ll search for the first instance of it and replace it.

To search all instances of it and replace all of them, we need to use a regex:

let newText = text.replace(/World War II/g, "the Second World War");

The g flag stands for global. This means it’ll replace all of them.

Rounding Numbers

We can use the Math.round method to round numbers.

For example, we can write:

let score = Math.round(11.1);

Then we round 11.1 to 11 with Math.round .

It rounds to the nearest integer.

The function rounds up when the decimal is .5.

To always round up to the nearest integer, we can use the Math.ceil method:

let score = Math.ceil(11.1);

Then we get 12.

To always round down to the nearest integer, we can use the Math.floor method:

let score = Math.floor(11.1);

Generating Random Numbers

JavaScript comes with a function to generate random numbers.

The Math.random method lets us create a random number between 0 and 1.

For example, we can write:

let randomNumber = Math.random();

The returned number has 16 decimal places.

Converting Strings to Integers and Decimals

Convert strings with numbers to an integer or decimal number is something that we often have to do.

We can use the parseInt method to convert a string into an integer.

And we can use the parseFloat method to convert a string into a decimal number.

For example, we can write:

let currentAge = prompt("Enter your age.");
let age = parseInt(currentAge);

We have the parseInt method to convert the entered number into an integer.

prompt always returns a string, so we’ll have to convert it to an integer.

To convert the entered text into a decimal number, we can use parseFloat :

let currentAge = prompt("Enter your age.");
let age = parseFloat(currentAge);

Converting Strings to Numbers and Vice Versa

To convert a string to a number, we can use the Number global function:

let num = Number('123');

Then num is 123 .

To convert a number to a string, we can use the toString method:

let num = 1234;
let numberAsString = num.toString();

The numberAsString is '1234' .

Conclusion

We can find and replace strings within a string.

Also, we can convert between numbers and strings and generate numbers with JavaScript.

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

Highlights of JavaScript —Looping, Adding, and Removing Array Elements

To learn JavaScript, we must learn the basics.

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

Adding and Removing elements

We can add and remove array elements easily with JavaScript.

To add elements, we just assign a value to the array index we want.

For example, we can write:

let animals = [];
animals[0] = "dog";
animals[1] = "cat";
animals[2] = "mouse";

We created the animals array by creating a variable and assigning it to an empty array.

Then we assign values to the given index of animals .

We can do this for any index and the indexes don’t have to be consecutive or in order.

To remove the last item from the array, we call the pop method:

animals.pop()

An alternative to add elements to an array is to use the push method:

animals.push("fish", "bird");

push adds elements to the end of the array.

To remove the first element of an array, we can shift :

animals.shift();

To add one more elements to the beginning of an array, we call unshift :

animals.shift("fish", "bird");

The splice method insert one or more elements anywhere in the array:

pets.splice(2, 2, "pig", "duck", "emu");

The first argument is the starting index to insert.

The 2nd is number of items to remove.

The subsequent arguments are the items we want to insert in place of the removed items.

The slice method lets us copy one or more consecutive elements in any position and put them in a new array.

For example, we can write:

let pets = animals.slice(2, 4);

to copy the items from index 2 to 3 from animals and return that array.

The first argument is the starting index copy. The 2nd is 1 after the ending index to copy.

The 2nd index itself isn’t included in the range.

for loops

Loops are provided by JavaScript so we can run code repeatedly.

To do this, we can use the for loop:

for (let i = 0; i <= 10; i++) {
  if (city === cleanestCities[i]) {
    console.log("It's one of the cleanest cities");
  }
}

A for loop is composed of the heading, which has the starting index, the condition to continue running the loop, and a statement to update the index.

In the loop body, we can do what we want.

In the example above, we check it city is equal to cleanestCities[i] .

And if it’s true , we console log a message.

The loop index is used for accessing the array item and also to move the loop towards the ending condition, which is i <= 10 .

If i is bigger than 10, then the loop stops.

We can also set flags in for loops so that we can record some information/

For example, we can write:

let matchFound = false;
for (let i = 0; i <= 10; i++) {
  if (city === cleanestCities[i]) {
    matchFound = true;
    console.log("It's one of the cleanest cities");
  }
}

We set matchFound to true once we found a value from cleanesCities that’s equal to city .

Conclusion

We can add and remove elements with JavaScript array methods.

Also, we can loop through array items with a for loop.

Categories
JavaScript Basics

Highlights of JavaScript — Conditions and Arrays

To learn JavaScript, we must learn the basics.

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

Testing Sets of Conditions

We can test more than one condition with an if statement.

To combine them, we can use the && or || operators.

&& is the logical AND operator and || is the logical OR operator.

For example, we can write:

if (weight > 300 && time < 6) {
  alert("athlete");
} else {
  alert("chef");
}

to check the value of weight and time together.

If weight is less than 300 and time is less than 6, then the first block is run.

Otherwise, then 2nd block is run.

We can chain more conditional together:

if (weight > 300 && time < 6 && age > 17 && gender === "male") {
  alert("athlete");
} else {
  alert("chef");
}

This will test if all the conditional are true . If they’re all true , then the first block is run,

Otherwise, the 2nd block is run.

The || operator can be used in a similar way.

For example, we can write:

if (SAT > avg || GPA > 2.5 || sport === "football") {
  alert("accepted");
} else {
  alert("not accepted");
}

The || operator returns true if any of the conditional returns true .

We can mix || and && together.

For example, we can write:

if (age > 65 || age < 21 && res === "U.S.")

The && takes precedence, so res === “U.S.” is evaluated first.

And the || operator is evaluated next.

To make this clearer, we should surround the expressions with parentheses so everyone can read it easily:

if ((age > 65 || age < 21) && res === "U.S.")

Nested if Statements

We can nest if statements. For example, we can write:

if (c === d) {
  if (x === y) {
    g = h;
  } else if (a === b) {
    g = h;
  } else {
    v = u;
  }
} else {
  v = u;
}

We nest the inner expressions with 2 spaces to make them easy to type and readable.

We shouldn’t have too many levels of nesting since it’s hard to read.

Arrays

There’s often a need to store many values in our programs.

To make this easier, we can use arrays.

For example, instead of repeatedly declaring variables to store similar values:

let city0 = "Oslo";
let city1 = "Rome";
let city2 = "Toronto";
let city3 = "Denver";
let city4 = "Los Angeles";
let city5 = "Seattle";

We can put them all into an array by writing:

let cities = ["Oslo", "Rome", "Toronto", "Denver", "Los Angeles", "Seattle"];

Arrays are very useful for storing a list of data that are fixed size or dynamic size.

We can access an array entry by its index.

For example, we can write:

cities[2]

JavaScript can be an array with different types. For example, we can write:

let mixedArray = [1, "james", "mary", true];

The index of the first entry is 0. The same naming rules for variables apply to arrays.

Arrays can only be declared once like other variables.

Conclusion

We can test more than one condition with if statements.

They can also be nested.

Arrays are useful for storing a collection of data.

Categories
JavaScript Basics

Highlights of JavaScript — Conditional Statements

To learn JavaScript, we must learn the basics.

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

if Statements

If statements let us run code conditionally.

For example, we can write:

const answer = prompt("Where's the capital of Italy?");  
if (answer === "Rome") {  
  alert("Correct!");  
}

to add a prompt to take in an answer to the question.

Then we check for it in th if statement. If answer is 'Rome' , then we show the 'Correct!' alert.

An if statement if followed by a boolean expression we’re checking for.

If the boolean expression returns true , then we run the code between the curly brace.

We should always use === to check for value equality since it checks for the type and value.

Simple if statements may be written without curtly brackets or the statement may be written all in one line.

But it’s more convenient to read to have the curly braces because it’s clearer.

Comparison Operators

The === operator is the comparison operator.

It’s the equality operator.

It’s used to compare 2 things to see if they’re equal.

We can use the equality operator to compare the return value of any 2 expressions.

For example, we can write:

if (totalCost === 81.50 + 100) {

or

if (fullName === firstName + " " + "wong") {

String comparisons are case-sensitive, so only if both cases are the same then the strings are considered the same.

If we want to check if 2 expressions aren’t the same, then we can use the !== inequality comparison operator.

So if we have:

"Rose" !== "rose"

then that returns true since they have letters with different cases.

JavaScript comes with more operators.

They include > for the greater-than operator.

< is the less-than operator.

>= is the greater than or equal to operator.

<= is the less than or equal to operator.

We can use them by writing:

if (2 > 0) {  
if (0 < 2) {  
if (2 >= 0) {  
if (2 >= 1) {  
if (0 <= 2) {  
if (1 <= 2) {

if…else and else if Statements

If we have more than one case to check for then we can use the else keyword to add more cases.

For example, we can write:

const answer = prompt("Where's the capital of Italy?");  
if (answer === "Rome") {  
  alert("Correct!");  
} else {  
  alert("Wrong!");  
}

The else keyword is before the block that’s run when answer isn’t 'Rome' .

If we have more cases, then we can add the else if statement.

For example, we can write:

const answer = prompt("Where's the capital of Italy?");  
if (answer === "Rome") {  
  alert("Correct!");  
} else if (answer === "Vatican") {  
  alert("Close!");  
} else {  
  alert("Wrong!");  
}

We run something is answer is 'Vatican' .

If answer isn’t 'Rome' or 'Vatican' , then we run the last block.

Conclusion

JavaScript has the if and else keywords to let us create statements that let us run code conditionally.