Categories
JavaScript Tips

Useful JavaScript Tips — Checking Strings and Styling Elements

Like any kind of apps, JavaScript apps also have to be written well.

Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

Get the Last Occurrence of a Substring in a String

The lastIndexOf method returns the index of the last occurrence of a substring in a string.

For instance, we can write:

'jane, joe, and joe'.lastIndexOf('joe')

Then we get 15.

It returns -1 if the substring isn’t found.

Get the First Occurrence of a Substring in a String

The indexOf method returns the index of the first occurrence of a substring in a string.

For instance, we can write:

'jane, joe, and joe'.indexOf('joe')

Then we get 6.

It returns -1 if the substring isn’t found.

Check if a Substring is in a String

We can check if a substring is in a string with the includes method.

For instance, we can write:

'jane, joe, and alex'.includes('joe')

Then it returns true .

Otherwise, if we have:

'jane, joe, and alex'.includes('foo')

then it returns false .

It also takes a second argument to indicate which index we want to start the search.

For example, we can write:

'jane, joe, and alex'.includes('joe', 10)

then it returns false .

Check if a String Ends with a Substring

The endsWith method lets us check if a string ends with a substring.

For example, we can write:

'jane, joe, and alex'.`endsWith`('alex')

then it returns true .

We can also pass in an integer to search for a substring with the given length of the string.

For example, we can write:

'jane, joe, and alex'.`endsWith`('alex', 5)

Then it returns false since 'alex' isn’t in the first 5 characters of the string.

Combining 2 or More Strings

The concat method lets us combine 2 or more strings.

For instance, we can write:

'jane'.concat(' ', 'smith');

to get 'jane smith' .

Also, we can write:

'jane'.concat(' ').concat('smith');

to get the same thing.

Get the Unicode Character Code of a Character

The charCodeAt method lets us get the character code of a character./

For instance, if we have:

'a'`.charCodeAt(0)`

Then we get 97 .

We can also use the codePouintAt method:

'a'`.codePointAt(0)`

to get the same result.

Get a Character from a String by Index

The charAt method lets us get the character by its index.

For example, we can write:

'jane'.charAt(0)

to return 'j' .

Find the Location of a Substring that Matches a Given Pattern

The search method lets us search for a substring with the given pattern.

For instance, we can write:

'jane, joe, and alex'.`search`('jane')

Then we get 0.

We can also search with a regex.

For example, we can write:

'jane, joe, and alex'.search(/\b\[a-z\]{3}\b/)

Then we get 6.

If no match is found, then -1 is returned.

Replace a String with the Given Pattern with Another String

The replace method lets us replace a substring with the given pattern with the given substring.

For instance, we can write:

'jane, joe, and alex'.replace(/\b\[a-z]{3}\b/, 'may')

Then we get “jane, may, and alex” .

List All Methods of an Object

We can get all the methods of an object with Object.keys and the typeof operator.

For example, we can write:

const getMethods = (obj) => Object.keys(obj).filter(key => typeof obj\[key\] === 'function')

Object.keys only get noninherited string properties of an object.

So if we have:

const person = {
  name: 'james',
  eat() {},
  drink() {}
}

Then we can call getMethods by writing:

`getMethods(`person)

And get [“eat”, “drink”] .

Style a DOM Element

We can style an element in various ways.

We can add or remove classes from an element.

Also, we can add inline styles to it.

Given that we have the following element:

const element = document.querySelector('#foo')

We can use the classList property of the element to add and remove classes:

element.classList.add('fancy')
element.classList.remove('fancy')

Also, we can access the style property as follows.

We can write:

element.style.color = 'green';

Adding and removing classes are preferred because it’s faster than changing styles on the fly.

Conclusion

We can add styles to an object by using the styles property.

The classList property lets us add or remove classes from an element.

There are string methods to get the info we need from a string.

Also, we can replace and search for substrings.

Categories
JavaScript Tips

Useful JavaScript Tips — Variables, File Names, and Console

Like any kind of apps, JavaScript apps also have to be written well. Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

var and let

var is function scoped and let is block-scoped.

var is hoisted and let isn’t.

Only the variable is hoisted, but the value isn’t.

For instance, if we have:

console.log(x);
var x = 1;

then x would be undefined since var x is hoisted but 1 is not.

On the other hand, we can’t do the same thing with let :

console.log(x);
let x = 1;

We’ll get an error with the code above since we can’t use let variables unless they’ve been declared.

To reduce confusion, we should use let variables.

Breaking the forEach Iteration

We can return true inside the callback that we pass into forEach to skip an itreration.

This way, we can have the same functionality as continue .

For instance, we can write:

[0, 1, 2, 3, 4].forEach((val, i) => {
  if (val === 2) {
    return true;
  }
  console.log(val);
});

The code about would skip 2 since when val is 2, then we returned true .,

So we skipped the console log that’s below it.

Using Slice

The slice method can be used to get array entries from an array.

We can start with a negative index to return array entries from the right instead of the left.

So if we have:

const arr = [1, 2, 3];

Then:

arr.slice(-1)

returns [3] .

arr.slice(-2))

returns [2, 3] .

and:

arr.slice(-3)

returns the original array.

This is because -1 is the index of the last element of the array.

-2 is the second last and so on.

Short Circuit Conditionals

Short circuit conditionals are handy since we can do things with && and || that we might not have thought of.

For instance, instead of writing:

if(condition){
    dosomething();
}

We can write:

condition && dosomething();

since the doSomething is only run when condition is truthy with the && operator.

Likewise, we can take advantage of short-circuiting with the || operator.

For instance, we can write:

a = a || 'default';

since a is assigned to a if a is truthy.

Otherwise, 'default' is assigned to a .

Use Optional Arguments

We can make arguments optional with the default parameter syntax.

For instance, we can write:

const divide = (a, b = 1) => a / b;

Then b would be assigned to 1 if we skipped the argument.

So divide(2) would be 2.

Copy Things to the Clipboard

We can get the element from a clipboard and copy its contents by writing:

document.querySelector('#foo').select();
document.execCommand('copy');

The first line selects the element with ID foo .

Then the second line does the copying.

Extract File Extension from a File Name

There are a few ways that we can extract the file extension from the file name

Regex

For instance, we can write:

const getExt = (filename) => {
  return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename)[0] : undefined;
}

We have a regex to split the file name by the dot. Then we get the part after the dot with /[^.]+$/.exec(filename)[0] or undefined if there’s no dot.

split

Also, we can use the split method to split a file name by the dot.

For example, we can write:

const getExt = (filename) => {
  return filename.split('.').pop();
}

A string has the split method which can split a string by a separator and returns it as an array of strings.

Then we call pop to remove the last part of the split string and returns it.

Therefore, we get the extension.

Console Logging Trick

We can use the && to run console log before evaluating the expression after it.

Since console.log returns undefined the right operand will always be evaluated.

So we can write:

console.log(foo) && false

We logged the value of foo and return false all in one expression.

Print a Function to a Console

We can convert a function to a string to print out the function’s code.

For instance, we can write:

console.log(func.toString());

This way, we can see the code of the function in the console log.

Conclusion

We can log a function’s code in with the toString and console.log methods.

Also, we can use the && operator to log a value before evaluating some other expression.

There are also various ways to get the file extension from a file name.

Finally, we should use let to declare variables as much as possible.

Categories
JavaScript Tips

Useful JavaScript Tips — Strings

Like any kind of apps, JavaScript apps also have to be written well.

Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

Convert Strings to Uppercase

We can call toUpperCase to change the string characters to uppercase.

For instance, we can write:

'foo'.toUpperCase()

then it returns 'FOO' .

Convert Strings to Lowercase

To convert a string to lowercase, we can use the toLowerCase method.

For instance, we can write:

'FOO'.`toLowerCase`()

then it returns 'foo' .

Converting Strings to Uppercase in a Locale-Sensitive Way

We can use the toLocaleUpperCase method to convert a string into a locale-sensitive upper case string.

For instance, we can write:

'foo'.toLocaleUpperCase('tr');

Then we get “FOO” .

Converting Strings to Lowercase in a Locale-Sensitive Way

There’s the toLocaleLowerCase method to convert a string into a locale-sensitive lowercase string.

For instance, we can write:

'FOO'.toLocaleLowerCase('tr');

Then we get “foo” .

Extracting a Substring From a String

To extract a substring from a string, we can use the substring method.

It takes a start and ending index of a string.

For instance, we can write:

'jane, joe, and alex'.substring(5, 10);

and that returns “ joe,” .

The index can also be negative.

So we can write:

'jane, joe, and alex'.substring(-10, 4);

and get 'jane' .

Negative indexes start from -1 which is the index of the last character, -2 is the index of the 2n last character, and so on.

Check if a String Starts With Something

Strings have a startsWith method that we can use to check if a string starts with a given substring.

For instance:

'jane, joe, and alex'.`startsWith`('jane');

returns true .

On the other hand;

'jane, joe, and alex'.`startsWith`('foo');

returns false .

It also takes a second argument to make startsWith starts the search from a given index.

For instance, we can write:

'jane, joe, and alex'.`startsWith`('jane', 5);

Then startsWith starts searching with index 5.

Split a String According to a Separator

We can call split according to a separator.

For instance, we can write:

'jane, joe, and alex'.`split`(' ');

Then we split the string according to the space characters.

So we get [“jane,”, “joe,”, “and”, “alex”] as the result.

Extract a Slice of a String

The slice method can help with extracting a substring from a string.

It takes a start and end index.

For instance, we can write the following code:

'jane, joe, and alex'.`slice`(5, 10)

Then that returns the string “ joe,” .

It also takes negative indexes, with -1 being the last character, -2 being the 2nd last, and so on.

For instance, we can write:

'jane, joe, and alex'.`slice`(-10, -5)

and it returns “, and” .

Make a String Repeat

The repeat method can make a string repeat.

For instance, we can write:

'fooo'.repeat(3)

Then we get “fooofooofooo” .

Adding Characters to the Beginning of the String

The padStart method takes an argument for the target length of the string after padding.

The 2nd argument is the string to pad our string with.

For instance, we can write:

‘foo’.padStart(8, ‘abcd’)

Then it returns “abcdafoo” since it pads 'foo' with 'abcd' repeated until the returned string has 8 characters.

Adding Characters to the End of the String

The padEnd method takes an argument for the target length of the string after padding to the end.

The 2nd argument is the string to pad our string with.

For instance, we can write:

‘foo’.`padEnd`(8, ‘abcd’)

Then we return “fooabcda” since we add the string to the end of the string.

Removing Extra Unicode Characters

We can use normalize to remove extra characters by replacing them with single-character equivalents.

For instance, we can write:

'\u1E9B\u0323'.normalize()

Then we get “ẛ̣” .

Find the String Matches a Given Regex Pattern

The match method returns the matches of a given regex pattern.

For instance, we can write:

'foo'.match(/(foo|bar)/)

Then that would return [ "foo", "foo" ] .

Compare Strings by Using the Locale Compare

localeCompare compares the strings in a locale-sensitive way.

For instance, we can write:

'a'.localeCompare('à', 'fr-ca')

Then that returns -1 since ‘à’ is behind 'a' .

Conclusion

There are string methods that we can do many things with.

We can compare strings and pad them to a given length.

Categories
JavaScript Tips

Useful JavaScript Tips — Operators

Like any kind of apps, JavaScript apps also have to be written well. Otherwise, we can run into all kinds of issues later on. In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

Ternary Operator

The ternary lets us return expressions according to a condition. It takes 3 operands.

For instance, we can write:

const eating = true;
(eating) ? stop() : eat()

We check if eating is true and call stop() and return its value if it is. Otherwise, we call eat and return its value.

Logical Operators

JavaScript has a few logical operators. We have the and, or, and not operators. The and-operator returns true if both operands and true.

For instance, we write:

a && b > 10

It can also do checks on the first operand and evaluate the second operand if the first is truthy.

So we can write:

const color = dog && dog.color;

Then dog.color is evaluated only if dog is truth. The or operator returns true if at least one of the operands is true .

For instance, we can write:

a || b > 10

It’s also very useful for providing a default value. For example, we can write:

const color = dog.color || 'brown';

The expression evaluates dog.color and if it’s falsy, then 'brown' will be returned. The not operator is used to invert the value of a boolean.

For instance, we can write:

let foo = true
!foo

Then !foo is false since foo is true .

Return Values

Every JavaScript function returns a value. If a function doesn’t have an explicit return statement or have a return statement that doesn’t have an expression after it, then it returns undefined .

For instance, we can write:

const foo = () => {
  return 'bar';
}

Then it returns 'bar' . A return statement can only return one value. If a function return arrays then we can use destructuring syntax to decompose the entries into variables.

For instance, we can write:

const foo = () => {
  return ['james', 10];
}
const [name, age] = foo();

The returned array is decomposed into variables according to their position. Likewise, we can do the same thing if a function returns an object.

For instance, we can write:

const foo = () => {
  return { name: 'james', age: 10 };
}
const { name, age } = foo();

This way we decompose the returned object into variables by their property names.

Spread Operator

The spread operator is used to expand an array, object, or string,

For instance, we can use it to spread array entries into another array:

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

Then b os [1, 2, 3, 4, 5] .

We can copy an array by writing:

const copy = [...a];

It also works with objects, we can clone an object by writing:

const copyObj = { ...obj };

We can spread a string into an array of characters using the spread operator:

const hello = 'hello';
const arr = [...hello];

Then arr is [“h”, “e”, “l”, “l”, “o”] . The spread operator can also be used to spread an array.

For instance, we can write:

const foo = (a, b) => {};
const a = [1, 2];
foo(...a);

We spread the a array into the arguments of foo , so a is 1 and 1bis 2.

The rest operator lets us get the array entries that haven’t been spread by writing:

const nums = [1, 2, 3, 4, 5];
const [one, two, ...rest] = nums;

The one is 1, two is 2, and rest has an array with the remaining nums entries. Likewise, we can do the same with objects.

For instance, we can write:

const {
  foo,
  bar,
  ...others
} = {
  foo: 1,
  bar: 2,
  a: 3,
  b: 4,
  baz: 5
}

We used the rest operator which has the object with the properties that haven’t been destructured. Also, we can use the spread operator to merge 2 objects together.

For instance, we can write:

const obj1 = {
  name: 'james'
}

const obj2 = {
  age: 15
}

const person = {...obj1, ...obj2 }

We combined obj1 and obj2 into a single person object using the spread operator.

Conclusion

There are many uses for the spread and rest operators with arrays and objects. The ternary operator can be used to replace short conditions. Functions always return some value either implicitly or explicitly.

Categories
JavaScript Tips

Useful JavaScript Tips — Object Properties and Copying

Like any kind of apps, JavaScript apps also have to be written well.

Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

Comparing 2 Objects with Object.is()

An alternative way to compare 2 objects is with the Object.is method.

It’s almost the same as the === operator.

However, NaN is the same as itself.

For instance, we can write:

Object.is(a, b)

Then we can compare 2 variables a and b .

Get the Prototype of an Object

We can get the prototype of an object with the Object.getPrototypeOf method.

For instance, we can get the prototype of an object as follows:

const animal = {
  name: 'james',
  age: 7
};

const dog = Object.create(animal);

We created a dog object with Object.create so that dog will inherit from animal .

So if we call Object.gerPrototypeOf with it:

const prot = Object.getPrototypeOf(dog);

Then:

prot === animal

would be true since animal is dog ‘s prototype.

Get the Non-inherited Symbols of an Object

The Object.getOwnPropertySymbols returns all the non-inherited symbol keys of an object.

If we have the follow object:

const name = Symbol('name')
const age = Symbol('age')
const dog = {
  [name]: 'james',
  [age]: 7
}

Then we can call getOwnPropertySymbols as follows:

const syms = Object.getOwnPropertySymbols(dog);

Then we get that syms is :

[Symbol(name), Symbol(age)]

Get Non-inherited String Keys of an Object

The Object.getOwnPropetyNames method lets us get an array of string keys of an object.

The keys return aren’t inherited from any prototypes.

For instance, we can write:

const dog = {
  breed: 'poodle'
}

const keys = Object.getOwnPropertyNames(dog);

Then we get [“breed”] as the value of keys .

Get Key-Value Pairs of an Object

The Object.entries method returns an array of key-value pairs of an object.

For example, we can write:

const person = { name: 'james', age: 18 }
const pairs = Object.entries(person);

Then pairs would be:

[
  [
    "name",
    "james"
  ],
  [
    "age",
    18
  ]
]

where the first entry of the inner arrays is the key name, and the 2nd is the value.

Add a Single Property to an Object

We can call Object.defineProperty on an object to create a new property.

For instance, we can write:

const dog = {};
Object.defineProperty(dog, 'breed', {
  value: 'poodle'
})

We added the breed property into dog using the defineProperty method.

Add Multiple Properties to an Object at Once

In addition to the Object.defineProperty , there’s also the Object.defineProperties method to add multiple properties to an object.

For instance, we can write:

const dog = {};
Object.defineProperty(dog, {
  breed: {
    value: 'poodle'
  },
  name: {
    value: 'james'
  },
})

Then dog would be {breed: “poodle”, name: “james”} .

It’s a convenient way to add multiple properties to an object at once.

Creating an Object with Object.create

Object.create lets us create an object with a prototype.

For instance, we can write:

const animal = {
  name: 'james',
  age: 7
};

const dog = Object.create(animal);

Then dog is has animal as its prototype.

It’ll inherit all the properties from animal .

So dog.name would be 'james' .

Copying and Combining Objects with Object.assign

Object.assign lets us combine multiple objects into one or copy them.

To make a copy of an object, we can write:

const copy = Object.assign({}, original)

We make a copy of the original object and assigned it to the copy variable.

{} should be the first argument so that we won’t modify any existing objects and copy them into an empty object.

To combine multiple objects, we can write:

const merged  = Object.assign({}, obj1, obj2)

We copy all the own string properties from obj1 and obj2 into the empty object in the first argument.

So merged would have all the own properties from both.

Conclusion

We can compare and copy objects with static Object methods.

Also, we can define properties on an object with them.

Also, we can copy and merge objects with the Object.assign method.

It does a shallow copy so that the top-level is copied.