Kriza Educa

Kriza Educa

1599462121

Some of the best shortcuts when writing Javascript and Typescript

Everyone knows that Javascript and Typescript have several weird and hidden features that allow you to shorten the amount of code you write. To preface this article, I’d like to impose upon you an important tidbit of information, short and efficient code doesn’t always equal good code. As always, you should be prioritizing readability over implementing a bunch of fancy features.

That being said, these features can help you save tons of space and used properly are easily understandable to anyone else who’s reading your code. Let’s go over some of these shorthand features so that you can use and understand them in your code.

1. The Ternary Operator

This is probably the most well-known shorthand Javascript function, the shortened “if-else” statement. By using this operator, you can remove a lot of the if else boilerplate and turn four lines into one!

let v = true;

// Traditional approach
if (v) {
	console.log('True');
} else {
	console.log('False');
}

// Ternary Operator
v ? console.log('True') : console.log('False');

The structure is as follows: <conditional expression> ? <true case> : <false case?. Pretty simple, right? This is a great way to do one line if else operations and is especially useful when combined with other shorthand operators.

2. Typescript’s Constructor Shorthand

This one is particularly for Typescript (Sorry vanilla JS users), but is a great feature when building classes.

Normally in a class, you have to list all your class variables then reassign them in your constructor, which takes tons of lines of code. But if your class is relatively simple (you’re just assigning parameters to private variables), Typescript has a great way to cut the amount of code you write.

// Normal way
class Location {
	private _latitude: string;
	private _longitude: string;

	constructor(latitude: string, longitude: string) {
		this._latitude = latitude;
		this._longitude = longitude;
	}
}

// Shorthand in TypeScript
class Location {
	constructor(
		private _latitude: string,
		private _longitude: string
	) {}
}

On larger classes with tons of properties, this can be a real lifesaver!

3. Nullish Operator

Often misunderstood, the nullish operator lets you easily evaluate an expression and check if it’s null, and return a default value if it is null.

function nullish(value1, value2) {
	// If value1 is null returns 'default'
	let v1 = value1 ?? 'default';
	return v1 + value2;
}

myFn("this has no") //returns "this has no default"
myFn("this has no", 0) //returns "this has no 0"

Actually, technically it checks for null or undefined, but the name is close enough. This is a great way to check if values exist or not.

4. Object Property Assignment

ES6 simplified the process of assigning values to objects. If values are assigned to variables named exactly as the object’s properties, you won’t have to repeat the name!

let name: string = "Caelin";
let age: number = 18;

interface User {
	name: string;
	age: number;
}

// Old way (manual assignment)
let user1: User = {
	name: name,
	age: age,
}

// New way!
let user2: User = {
	name,
	age,
}

As shown above, the new way is considerably simpler and DRYer than the old way!

5. Arrow/Lambda Functions

If you’ve seen a lot of these operators: => thrown around everywhere, they’re arrow functions. These allow you to save a return statement since any lamda function will have a default return.

You’ll seen them often used in array operators as such:

let arr = [1, 2, 3, 4, 5];

// Long way
arr.map(function (n) {
	return n*2;
})

// Short way
arr.map(n => n*2);

As you can see, it makes the code considerably more readable and shorter.

6… Default Parameter Values

ES6 now allows you to specify default parameter values on functions! Before, you’d have to rely on OR’s lazy evaluation, which worked but was a suboptimal solution.

// Assigns 'c' a default value
function defaultParams(a, b, c="c") {
	return a + b + c;
}

Fun tip, if you want to make a required parameter, do the following:

const requiredParam = _ => throw new Error('Required Parameter!');

// Create a default parameter d
function defaultParamRequired(a, b, c="c", d=requiredParam()) {
	// Logic
}

Now, if this function runs without passing a default parameter d in, it’ll throw an error! Pretty cool trick right?

7. Destructuring and Spread Operators

I literally wrote a whole article on spread operators, but spread and destructing operations are great ways to take advantage of objects and arrays!

Destructuring

It’s quite common to want to access object parameters individually (to modify or read them) without accessing the original object. Normally, this would require a line for each object parameter, which can get quite long on larger objects. Object destructuring allows us to cut that into one line!

const user = {
	name: 'Caelin',
	age: 18,
}

// Normal method
const name = user.name;
const age = user.age;

// Destructuring method
const {name, age} = user;

This syntax is great for object parameters and import statements to reduce the number of lines when dealing with complex objects.

Spreading

Spread operators make it easier to combine objects and arrays by expanding them.

const arr1 = [1,2,3,4]
const arr2 = [5,6,7]

const finalArr = [...arr1, ...arr2] // [1,2,3,4,5,6,7]

const partialObj1 = {
  name: "fernando"
}
const partialObj2 = {
  age:37
}

const fullObj = { ...partialObj1, ...partialObj2 } // {name: "fernando", age: 37}

Conclusion

These are just a few of the many Javascript and Typescript shortcuts that can save you time and make your code cleaner. Remember, this is not simply about making code more efficient or reducing lines, it’s about making code that’s cleaner and easier to read for the next developer.

Did I miss something? Be sure to comment it down below!

Keep in Touch

There’s a lot of content out there, I appreciate you reading mine. I’m a young entrepreneur and I write about software development and my experience running companies.

Originally published on Medium.com

#web-development #typescript #javascript

What is GEEK

Buddha Community

Some of the best shortcuts when writing Javascript and Typescript

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

Kriza Educa

Kriza Educa

1599462121

Some of the best shortcuts when writing Javascript and Typescript

Everyone knows that Javascript and Typescript have several weird and hidden features that allow you to shorten the amount of code you write. To preface this article, I’d like to impose upon you an important tidbit of information, short and efficient code doesn’t always equal good code. As always, you should be prioritizing readability over implementing a bunch of fancy features.

That being said, these features can help you save tons of space and used properly are easily understandable to anyone else who’s reading your code. Let’s go over some of these shorthand features so that you can use and understand them in your code.

1. The Ternary Operator

This is probably the most well-known shorthand Javascript function, the shortened “if-else” statement. By using this operator, you can remove a lot of the if else boilerplate and turn four lines into one!

let v = true;

// Traditional approach
if (v) {
	console.log('True');
} else {
	console.log('False');
}

// Ternary Operator
v ? console.log('True') : console.log('False');

The structure is as follows: <conditional expression> ? <true case> : <false case?. Pretty simple, right? This is a great way to do one line if else operations and is especially useful when combined with other shorthand operators.

2. Typescript’s Constructor Shorthand

This one is particularly for Typescript (Sorry vanilla JS users), but is a great feature when building classes.

Normally in a class, you have to list all your class variables then reassign them in your constructor, which takes tons of lines of code. But if your class is relatively simple (you’re just assigning parameters to private variables), Typescript has a great way to cut the amount of code you write.

// Normal way
class Location {
	private _latitude: string;
	private _longitude: string;

	constructor(latitude: string, longitude: string) {
		this._latitude = latitude;
		this._longitude = longitude;
	}
}

// Shorthand in TypeScript
class Location {
	constructor(
		private _latitude: string,
		private _longitude: string
	) {}
}

On larger classes with tons of properties, this can be a real lifesaver!

3. Nullish Operator

Often misunderstood, the nullish operator lets you easily evaluate an expression and check if it’s null, and return a default value if it is null.

function nullish(value1, value2) {
	// If value1 is null returns 'default'
	let v1 = value1 ?? 'default';
	return v1 + value2;
}

myFn("this has no") //returns "this has no default"
myFn("this has no", 0) //returns "this has no 0"

Actually, technically it checks for null or undefined, but the name is close enough. This is a great way to check if values exist or not.

4. Object Property Assignment

ES6 simplified the process of assigning values to objects. If values are assigned to variables named exactly as the object’s properties, you won’t have to repeat the name!

let name: string = "Caelin";
let age: number = 18;

interface User {
	name: string;
	age: number;
}

// Old way (manual assignment)
let user1: User = {
	name: name,
	age: age,
}

// New way!
let user2: User = {
	name,
	age,
}

As shown above, the new way is considerably simpler and DRYer than the old way!

5. Arrow/Lambda Functions

If you’ve seen a lot of these operators: => thrown around everywhere, they’re arrow functions. These allow you to save a return statement since any lamda function will have a default return.

You’ll seen them often used in array operators as such:

let arr = [1, 2, 3, 4, 5];

// Long way
arr.map(function (n) {
	return n*2;
})

// Short way
arr.map(n => n*2);

As you can see, it makes the code considerably more readable and shorter.

6… Default Parameter Values

ES6 now allows you to specify default parameter values on functions! Before, you’d have to rely on OR’s lazy evaluation, which worked but was a suboptimal solution.

// Assigns 'c' a default value
function defaultParams(a, b, c="c") {
	return a + b + c;
}

Fun tip, if you want to make a required parameter, do the following:

const requiredParam = _ => throw new Error('Required Parameter!');

// Create a default parameter d
function defaultParamRequired(a, b, c="c", d=requiredParam()) {
	// Logic
}

Now, if this function runs without passing a default parameter d in, it’ll throw an error! Pretty cool trick right?

7. Destructuring and Spread Operators

I literally wrote a whole article on spread operators, but spread and destructing operations are great ways to take advantage of objects and arrays!

Destructuring

It’s quite common to want to access object parameters individually (to modify or read them) without accessing the original object. Normally, this would require a line for each object parameter, which can get quite long on larger objects. Object destructuring allows us to cut that into one line!

const user = {
	name: 'Caelin',
	age: 18,
}

// Normal method
const name = user.name;
const age = user.age;

// Destructuring method
const {name, age} = user;

This syntax is great for object parameters and import statements to reduce the number of lines when dealing with complex objects.

Spreading

Spread operators make it easier to combine objects and arrays by expanding them.

const arr1 = [1,2,3,4]
const arr2 = [5,6,7]

const finalArr = [...arr1, ...arr2] // [1,2,3,4,5,6,7]

const partialObj1 = {
  name: "fernando"
}
const partialObj2 = {
  age:37
}

const fullObj = { ...partialObj1, ...partialObj2 } // {name: "fernando", age: 37}

Conclusion

These are just a few of the many Javascript and Typescript shortcuts that can save you time and make your code cleaner. Remember, this is not simply about making code more efficient or reducing lines, it’s about making code that’s cleaner and easier to read for the next developer.

Did I miss something? Be sure to comment it down below!

Keep in Touch

There’s a lot of content out there, I appreciate you reading mine. I’m a young entrepreneur and I write about software development and my experience running companies.

Originally published on Medium.com

#web-development #typescript #javascript

Hans  Marvin

Hans Marvin

1636269900

TypeScript option you want to enable beyond strict : noUncheckedIndexedAccess

strict (and its sub flag strictNullChecks) can really help prevent null and undefined errors in your runtime #JavaScript. However, it doesn't defend against invalid array and object access.

In this lesson we look at a flag that protects against rogue undefined that might end up in your #TypeScript if this flag is not enabled 

#typescript #javascript 

Rahul Jangid

1622207074

What is JavaScript - Stackfindover - Blog

Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.

Who invented JavaScript?

JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.

What is JavaScript?

JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.

Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.

JavaScript Hello World Program

In JavaScript, ‘document.write‘ is used to represent a string on a browser.

<script type="text/javascript">
	document.write("Hello World!");
</script>

How to comment JavaScript code?

  • For single line comment in JavaScript we have to use // (double slashes)
  • For multiple line comments we have to use / * – – * /
<script type="text/javascript">

//single line comment

/* document.write("Hello"); */

</script>

Advantages and Disadvantages of JavaScript

#javascript #javascript code #javascript hello world #what is javascript #who invented javascript

Niraj Kafle

1589255577

The essential JavaScript concepts that you should understand

As a JavaScript developer of any level, you need to understand its foundational concepts and some of the new ideas that help us developing code. In this article, we are going to review 16 basic concepts. So without further ado, let’s get to it.

#javascript-interview #javascript-development #javascript-fundamental #javascript #javascript-tips