Debbie Clay

Debbie Clay

1565797659

Top 12 Javascript Tricks for Beginners

In this article, I’ll share 12 hand-picked tips that strike me as particularly clever or useful. Useful tips for writing more concise and performant JavaScript.

When I began learning JavaScript, I made a list of every time-saving trick that I found in other people’s code, on code challenge websites, and anywhere other than the tutorials I was using.

I have been contributing to this list ever since, and in this article, I’ll share 12 hand-picked tips that strike me as particularly clever or useful.

While many of these tricks are handy in any context, one or two of them may be better suited for code golf than production-level code, where clarity is often more important than concision; I’ll let you be the judge of that!

So, in no particular order, here are 12 neat ways to write more concise and more performant code.

1. Filter Unique Values

ARRAYS

The Set object type was introduced in ES6, and along with ..., the ‘spread’ operator, we can use it to create a new array with only the unique values.

const array = [1, 1, 2, 3, 5, 5, 1]
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // Result: [1, 2, 3, 5]

Before ES6, isolating unique values would involve a lot more code than that!

2. Cache Array Length in Loops

LOOPS

When we are taught for loops, we are encouraged to follow this standard structure:

for (let i = 0; i < array.length; i++){
  console.log(i);
}

However, using this syntax, the for loop re-calculates the length of the array with every iteration.

This may be useful sometimes, but in most cases, it is better and more performant to cache the array’s length so that it only needs to be calculated once. We can do this by defining a length variable where we set our variable i , like so:

for (let i = 0, length = array.length; i < length; i++){
  console.log(i);
}

This code is almost as concise as the code above, but it means that as an array increases in size, no run-time is lost to re-calculating array.length .

3. Short-Circuit Evaluation

CONDITIONALS

The ternary operator is a quick way to write simple (and sometimes not-so-simple) conditional statements, like these:

x > 100 ? 'Above 100' : 'Below 100';
x > 100 ? (x > 200 ? 'Above 200' : 'Between 100-200') : 'Below 100';

But sometimes even the ternary operator is more complicated than necessary. Instead, we can use the ‘and’ && and ‘or’ || logical operators to evaluate certain expressions in an even more concise way. This is often called ‘short-circuiting’ or ‘short-circuit evaluation’.

How It Works

Let’s say we want to return just one of two or more options.

Using && will return the first false or ‘falsy’ value. If every operand evaluates to true , the last evaluated expression will be returned.

let one = 1, two = 2, three = 3;
console.log(one && two && three); // Result: 3
console.log(0 && null); // Result: 0

Using || will return the first true or ‘truthy’ value. If every operand evaluates to false , the last evaluated expression will be returned.

let one = 1, two = 2, three = 3;
console.log(one || two || three); // Result: 1
console.log(0 || null); // Result: null

Example 1

Let’s say we want to return the length of a variable, but we don’t know the variable type.

We could use an if/else statement to check that foo is an acceptable type, but this could get pretty longwinded. Short circuit evaluation allows us to do this instead:

let one = 1, two = 2, three = 3;
console.log(one || two || three); // Result: 1
console.log(0 || null); // Result: null

In both cases, if the variable foo has a length property, it will be returned. Otherwise, the length of the empty array will be returned: 0 .

Example 2

Have you ever had problems accessing a nested object property? You might not know if the object or one of the sub-properties exists, and this can cause frustrating errors.

Let’s say we wanted to access a property called data within this.state , but data is undefined until our program has successfully returned a fetch request.

Depending on where we use it, calling this.state.data could prevent our app from running. To get around this, we could wrap it in a conditional:

if (this.state.data) {
  return this.state.data;
} else {
  return 'Fetching Data';
}

But that seems pretty repetitive. The ‘or’ operator provides a more concise solution:

return (this.state.data || 'Fetching Data');

Unlike in Example 1, we can’t refactor the code above to use && . The statement 'Fetching Data' && this.state.data will return this.state.data whether it is undefined or not. This is because 'Fetching Data' is ‘truthy’, and so the && will always pass over it when it is listed first.

A New Proposed Feature: Optional Chaining

There is currently a proposal to allow ‘optional chaining’ when attempting to return a property deep in a tree-like structure. Under the proposal, the question mark symbol ? could be used to extract a property only if it is not null .

For example, we could refactor our example above to this.state.data?.() , thus only returning data if it is not null .

Or, if we were mainly concerned about whether state was defined or not, we could return this.state?.data .

The proposal is currently at Stage 1, as an experimental feature. You can read about it here, and you can use in your JavaScript now via Babel, by adding @babel/plugin-proposal-optional-chaining to your .babelrc file.

4. Convert to Boolean

TYPE CONVERSION

Besides the regular boolean values true and false , JavaScript also treats all other values as either ‘truthy’ or ‘falsy’.

Unless otherwise defined, all values in JavaScript are ‘truthy’ with the exception of 0, "", null, undefined, NaN and of course false , which are ‘falsy’.

We can easily switch between true and false by using the negative operator ! , which will also convert the type to "boolean" .

const true  = !0;
const false = !1;
const alsoFalse = !!0;
console.log(true); // Result: true
console.log(typeof true); // Result: "boolean"

This kind of type conversion can be handy in conditional statements, although the only reason you’d choose to define false as !1 is if you were playing code golf!

5. Convert to String

TYPE CONVERSION

To quickly convert a number of a string, we can use the concatenation operator + followed by an empty set of quotation marks "" .

const val = 1 + "";
console.log(val); // Result: "1"
console.log(typeof val); // Result: "string"

6. Convert to Number

TYPE CONVERSION

The opposite can be quickly achieved using the addition operator + .

let int = "15";
int = +int;
console.log(int); // Result: 15
console.log(typeof int); Result: "number"

This may also be used to convert booleans to numbers, as below:

console.log(+true);  // Return: 1
console.log(+false); // Return: 0

There may be contexts where the + will be interpreted as the concatenation operator rather than the addition operator. When that happens (and you want to return an integer, not a float) you can instead use two tildes: ~~ .

A tilde, known as the ‘bitwise NOT operator’, is an operator equivalent to-n — 1 . So, for example, ~15 is equal to -16 .

Using two tildes in a row effectively negates the operation, because — ( — n — 1) — 1 = n + 1 — 1 = n . In other words, ~ — 16 equals 15 .

const int = ~~"15"
console.log(int); // Result: 15
console.log(typeof int); Result: "number"

Though I can’t think of many use-cases, the bitwise NOT operator can also be used on booleans: ~true = -2 and ~false = -1 .

7. Quick Powers

OPERATIONS

Since ES7, it has been possible to use the exponentiation operator ** as a shorthand for powers, which is faster than writing Math.pow(2, 3) . This is straightforward stuff, but it makes the list because not many tutorials have been updated to include this operator!

console.log(2 ** 3); // Result: 8

This shouldn’t be confused with the ^ symbol, commonly used to represent exponents, but which in JavaScript is the bitwise XOR operator.

Before ES7, shorthand existed only for powers with base 2, using the bitwise left shift operator << :

// The following expressions are equivalent:
Math.pow(2, n);
2 << (n - 1);
2**n;

For example, 2 << 3 = 16 is equivalent to 2 ** 4 = 16 .

8. Quick Rounding

OPERATIONS

If you want to convert a float to an integer, you can use Math.floor() , Math.ceil() or Math.round() . But there is also a faster way using |, the bitwise ‘or’ operator.

console.log(23.9 | 0);  // Result: 23
console.log(-23.9 | 0); // Result: -23


The behaviour of | varies depending on whether you’re dealing with positive or negative numbers, so it’s best only to use this shortcut if you’re sure.

If n is positive, n | 0 rounds down. If n is negative, it rounds up. It effectively removes whatever comes after the decimal point. You can get the same rounding effect by using ~~, as above.

Remove Final Digits

The bitwise ‘or’ operator can also be used to remove any amount of digits from the end of an integer. This means we don’t have to use code like this to convert between types:

let str = "1553"; 
Number(str.substring(0, str.length - 1));

Instead, the bitwise ‘or’ operator allows us to write:

console.log(1553 / 10   | 0)  // Result: 155
console.log(1553 / 100  | 0)  // Result: 15
console.log(1553 / 1000 | 0)  // Result: 1

9. Automatic Binding in Classes

CLASSES

We can use ES6 arrow notation in class methods, and by doing so binding is implied. This will often save several lines of code in our class constructor, and we can happily say goodbye to repetitive expressions such as this.myMethod = this.myMethod.bind(_this_) !

import React, { Component } from React;
export default class App extends Compononent {
  constructor(props) {
  super(props);
  this.state = {};
  }
myMethod = () => {
    // This method is bound implicitly!
  }
render() {
    return (
      <>
        <div>
          {this.myMethod()}
        </div>
      </>
    )
  }
};

10. Truncate an Array

ARRAYS

If you want to remove values from the end of an array destructively, there’s no need to use slice() or splice() .

Simply re-define the length property of the array, like so:

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array.length = 4;
console.log(array); // Result: [0, 1, 2, 3]

Note that this trick only works for array.length and not for other types with a length property (such as strings or functions), nor for Set.prototype.size.

11. Get the Last Item(s) in an Array

ARRAYS

The array method slice() can take negative integers, and if provided it will take values from the end of the array rather than the beginning.

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(array.slice(-1)); // Result: [9]
console.log(array.slice(-2)); // Result: [8, 9]
console.log(array.slice(-3)); // Result: [7, 8, 9]

12. Format JSON Code

JSON

Lastly, you may have used JSON.stringify before, but did you realise it can also help indent your JSON for you?

The stringify() method takes two optional parameters: a replacer function, which you can use to filter the JSON that is displayed, and a space value.

The space value takes an integer for the number of spaces you want or a string (such as '\t' to insert tabs), and it can make it a lot easier to read fetched JSON data.

console.log(JSON.stringify({ alpha: 'A', beta: 'B' }, null, '\t'));
// Result:
// '{
//     "alpha": A,
//     "beta": B
// }'

Overall, I hope you found these tips as useful as I did when I first discovered them.

#javascript #web-development

What is GEEK

Buddha Community

Top 12 Javascript Tricks for Beginners
Ray  Patel

Ray Patel

1619518440

top 30 Python Tips and Tricks for Beginners

Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.

1) swap two numbers.

2) Reversing a string in Python.

3) Create a single string from all the elements in list.

4) Chaining Of Comparison Operators.

5) Print The File Path Of Imported Modules.

6) Return Multiple Values From Functions.

7) Find The Most Frequent Value In A List.

8) Check The Memory Usage Of An Object.

#python #python hacks tricks #python learning tips #python programming tricks #python tips #python tips and tricks #python tips and tricks advanced #python tips and tricks for beginners #python tips tricks and techniques #python tutorial #tips and tricks in python #tips to learn python #top 30 python tips and tricks for beginners

Sival Alethea

Sival Alethea

1624298400

Learn JavaScript - Full Course for Beginners. DO NOT MISS!!!

This complete 134-part JavaScript tutorial for beginners will teach you everything you need to know to get started with the JavaScript programming language.
⭐️Course Contents⭐️
0:00:00 Introduction
0:01:24 Running JavaScript
0:04:23 Comment Your Code
0:05:56 Declare Variables
0:06:15 Storing Values with the Assignment Operator
0:11:31 Initializing Variables with the Assignment Operator
0:11:58 Uninitialized Variables
0:12:40 Case Sensitivity in Variables
0:14:05 Add Two Numbers
0:14:34 Subtract One Number from Another
0:14:52 Multiply Two Numbers
0:15:12 Dividing Numbers
0:15:30 Increment
0:15:58 Decrement
0:16:22 Decimal Numbers
0:16:48 Multiply Two Decimals
0:17:18 Divide Decimals
0:17:33 Finding a Remainder
0:18:22 Augmented Addition
0:19:22 Augmented Subtraction
0:20:18 Augmented Multiplication
0:20:51 Augmented Division
0:21:19 Declare String Variables
0:22:01 Escaping Literal Quotes
0:23:44 Quoting Strings with Single Quotes
0:25:18 Escape Sequences
0:26:46 Plus Operator
0:27:49 Plus Equals Operator
0:29:01 Constructing Strings with Variables
0:30:14 Appending Variables to Strings
0:31:11 Length of a String
0:32:01 Bracket Notation
0:33:27 Understand String Immutability
0:34:23 Find the Nth Character
0:34:51 Find the Last Character
0:35:48 Find the Nth-to-Last Character
0:36:28 Word Blanks
0:40:44 Arrays
0:41:43 Nest Arrays
0:42:33 Access Array Data
0:43:34 Modify Array Data
0:44:48 Access Multi-Dimensional Arrays
0:46:30 push()
0:47:29 pop()
0:48:33 shift()
0:49:23 unshift()
0:50:36 Shopping List
0:51:41 Write Reusable with Functions
0:53:41 Arguments
0:55:43 Global Scope
0:59:31 Local Scope
1:00:46 Global vs Local Scope in Functions
1:02:40 Return a Value from a Function
1:03:55 Undefined Value returned
1:04:52 Assignment with a Returned Value
1:05:52 Stand in Line
1:08:41 Boolean Values
1:09:24 If Statements
1:11:51 Equality Operator
1:13:18 Strict Equality Operator
1:14:43 Comparing different values
1:15:38 Inequality Operator
1:16:20 Strict Inequality Operator
1:17:05 Greater Than Operator
1:17:39 Greater Than Or Equal To Operator
1:18:09 Less Than Operator
1:18:44 Less Than Or Equal To Operator
1:19:17 And Operator
1:20:41 Or Operator
1:21:37 Else Statements
1:22:27 Else If Statements
1:23:30 Logical Order in If Else Statements
1:24:45 Chaining If Else Statements
1:27:45 Golf Code
1:32:15 Switch Statements
1:35:46 Default Option in Switch Statements
1:37:23 Identical Options in Switch Statements
1:39:20 Replacing If Else Chains with Switch
1:41:11 Returning Boolean Values from Functions
1:42:20 Return Early Pattern for Functions
1:43:38 Counting Cards
1:49:11 Build Objects
1:50:46 Dot Notation
1:51:33 Bracket Notation
1:52:47 Variables
1:53:34 Updating Object Properties
1:54:30 Add New Properties to Object
1:55:19 Delete Properties from Object
1:55:54 Objects for Lookups
1:57:43 Testing Objects for Properties
1:59:15 Manipulating Complex Objects
2:01:00 Nested Objects
2:01:53 Nested Arrays
2:03:06 Record Collection
2:10:15 While Loops
2:11:35 For Loops
2:13:56 Odd Numbers With a For Loop
2:15:28 Count Backwards With a For Loop
2:17:08 Iterate Through an Array with a For Loop
2:19:43 Nesting For Loops
2:22:45 Do…While Loops
2:24:12 Profile Lookup
2:28:18 Random Fractions
2:28:54 Random Whole Numbers
2:30:21 Random Whole Numbers within a Range
2:31:46 parseInt Function
2:32:36 parseInt Function with a Radix
2:33:29 Ternary Operator
2:34:57 Multiple Ternary Operators
2:36:57 var vs let
2:39:02 var vs let scopes
2:41:32 const Keyword
2:43:40 Mutate an Array Declared with const
2:44:52 Prevent Object Mutation
2:47:17 Arrow Functions
2:28:24 Arrow Functions with Parameters
2:49:27 Higher Order Arrow Functions
2:53:04 Default Parameters
2:54:00 Rest Operator
2:55:31 Spread Operator
2:57:18 Destructuring Assignment: Objects
3:00:18 Destructuring Assignment: Nested Objects
3:01:55 Destructuring Assignment: Arrays
3:03:40 Destructuring Assignment with Rest Operator to Reassign Array
3:05:05 Destructuring Assignment to Pass an Object
3:06:39 Template Literals
3:10:43 Simple Fields
3:12:24 Declarative Functions
3:12:56 class Syntax
3:15:11 getters and setters
3:20:25 import vs require
3:22:33 export
3:23:40 * to Import
3:24:50 export default
3:25:26 Import a Default Export
📺 The video in this post was made by freeCodeCamp.org
The origin of the article: https://www.youtube.com/watch?v=PkZNo7MFNFg&list=PLWKjhJtqVAblfum5WiQblKPwIbqYXkDoC&index=4

🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#javascript #learn javascript #learn javascript for beginners #learn javascript - full course for beginners #javascript programming language

Lowa Alice

Lowa Alice

1624379820

JavaScript Tutorial for Beginners: Learn JavaScript in 1 Hour

Watch this JavaScript tutorial for beginners to learn JavaScript basics in one hour.
avaScript is one of the most popular programming languages in 2019. A lot of people are learning JavaScript to become front-end and/or back-end developers.

I’ve designed this JavaScript tutorial for beginners to learn JavaScript from scratch. We’ll start off by answering the frequently asked questions by beginners about JavaScript and shortly after we’ll set up our development environment and start coding.

Whether you’re a beginner and want to learn to code, or you know any programming language and just want to learn JavaScript for web development, this tutorial helps you learn JavaScript fast.

You don’t need any prior experience with JavaScript or any other programming languages. Just watch this JavaScript tutorial to the end and you’ll be writing JavaScript code in no time.

If you want to become a front-end developer, you have to learn JavaScript. It is the programming language that every front-end developer must know.

You can also use JavaScript on the back-end using Node. Node is a run-time environment for executing JavaScript code outside of a browser. With Node and Express (a popular JavaScript framework), you can build back-end of web and mobile applications.

If you’re looking for a crash course that helps you get started with JavaScript quickly, this course is for you.

⭐️TABLE OF CONTENT ⭐️

00:00 What is JavaScript
04:41 Setting Up the Development Environment
07:52 JavaScript in Browsers
11:41 Separation of Concerns
13:47 JavaScript in Node
16:11 Variables
21:49 Constants
23:35 Primitive Types
26:47 Dynamic Typing
30:06 Objects
35:22 Arrays
39:41 Functions
44:22 Types of Functions

📺 The video in this post was made by Programming with Mosh
The origin of the article: https://www.youtube.com/watch?v=W6NZfCO5SIk&list=PLTjRvDozrdlxEIuOBZkMAK5uiqp8rHUax&index=2
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#javascript #javascript tutorial #javascript tutorial for beginners #beginners

wp codevo

wp codevo

1608042336

JavaScript Shopping Cart - Javascript Project for Beginners

https://youtu.be/5B5Hn9VvrVs

#shopping cart javascript #hopping cart with javascript #javascript shopping cart tutorial for beginners #javascript cart project #javascript tutorial #shopping cart

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