#learn ecmascript 6
Explore tagged Tumblr posts
anyone-can-blog · 8 months ago
Text
ES6+ Features in JavaScript
Dive deep into the world of ES6+ features! This comprehensive guide covers everything from arrow functions to async/await. Learn how to write cleaner, more efficient JavaScript code. #javascript #es6 #programming #webdevelopment
Are you ready to take your JavaScript skills to the next level? In the day 8, we’ll explore the essential features introduced in ECMAScript 6 (ES6) that have revolutionized modern JavaScript development. From arrow functions to classes and modules, these features offer significant improvements in code readability, maintainability, and performance. Let’s dive in and discover how ES6+ can empower…
0 notes
soc-learning · 9 months ago
Text
11 Tips to Learn JavaScript Fast
Tumblr media
JavaScript is a crucial programming language for anyone looking to enter the world of web development. Mastering it can open doors to building dynamic websites, mobile applications, and even server-side applications. Whether you're a beginner or someone looking to sharpen your skills, learning JavaScript quickly requires a mix of dedication, practice, and smart strategies. Here are 11 tips to help you learn JavaScript faster.
1. Understand the Basics First
It’s tempting to jump straight into advanced concepts, but a strong foundation is key. Start by learning the basic syntax, data types, variables, loops, and conditionals. Get comfortable with how JavaScript fits into the broader ecosystem of web development, particularly how it works alongside HTML and CSS.
2. Break Down Complex Problems
When faced with a challenging problem, break it down into smaller tasks. This approach makes coding less overwhelming and helps you understand how different pieces of code interact with each other. Dealing with smaller problems also boosts your confidence as you master solving each one.
3. Practice, Practice, Practice
JavaScript isn’t something you can learn passively. Dedicate time every day to coding. The more you practice, the more natural it will become. Use online platforms like CodePen or JSFiddle to write and test your code, or build small projects that can help reinforce what you’ve learned.
4. Learn the DOM (Document Object Model)
One of JavaScript’s most powerful features is its ability to interact with the HTML DOM. Learn how to manipulate HTML elements using JavaScript. This will allow you to create interactive and dynamic websites, making your learning journey both fun and practical.
5. Use Debugging Tools
Errors are inevitable when coding, but learning how to debug effectively will save you time. Use the built-in developer tools in browsers like Chrome to inspect and debug your code. Understanding how to locate and fix errors will help you grow as a developer faster.
6. Work on Real Projects
Building real projects gives you hands-on experience with JavaScript. Start with small projects such as creating a simple calculator, a to-do list, or a quiz app. As your confidence grows, try tackling more complex projects that integrate APIs or frameworks like React.
7. Master Functions and Objects
JavaScript heavily relies on functions and objects. Understanding how to create and use functions effectively will help you write cleaner, more efficient code. Likewise, objects are essential for organising data and structuring your programs.
8. Learn ES6 Features
ES6 (ECMAScript 2015) introduced many new features that make JavaScript more powerful and developer-friendly. Familiarise yourself with important ES6 concepts like let, const, arrow functions, template literals, and promises. These will help you write more modern and efficient code.
9. Leverage JavaScript Libraries
JavaScript libraries like jQuery, Lodash, or even frameworks like React and Vue.js can help you learn faster by abstracting complex tasks. These tools allow you to focus on core learning without getting bogged down by repetitive coding tasks.
10. Join Developer Communities
Engage with fellow learners and developers by joining JavaScript communities online. Platforms like Stack Overflow, GitHub, or Reddit offer opportunities to ask questions, share knowledge, and collaborate on projects. Learning with a community not only accelerates your progress but also makes the journey more enjoyable.
11. Stay Consistent and Keep Learning
Learning JavaScript fast doesn’t mean cutting corners. Stay consistent in your practice and keep learning. JavaScript is always evolving, with new updates and frameworks emerging regularly. Keep yourself up to date with the latest trends and advancements in the language.
By following these tips and staying committed, you’ll be able to master JavaScript in no time. For additional insights, check out our blog on 10 JavaScript Tips and Tricks to Optimise Performance.
0 notes
softweb-solutions · 9 months ago
Text
Why Angular 18 Matters: Key Features and Updates You Need to Know
Tumblr media
Angular, the popular web application framework developed by Google, continues to evolve. With the release of Angular 18 on May 22, developers have much to look forward to. Angular 18 introduces a range of features and improvements aimed at enhancing performance, developer experience, and overall robustness. In this blog, we will delve into why Angular 18 matters, highlighting its top 20+ features and updates.
Why Angular 18 matters
Angular has consistently been a framework of choice for building robust, scalable, and maintainable web applications. Each new version of Angular brings enhancements that address existing pain points and introduces innovative features that align with modern web development practices. Angular 18 is no exception. It promises to improve developer productivity, application performance and user experience.
Key features and updates in Angular 18
1. Enhanced reactivity model
Angular 18 introduces an enhanced reactivity model that simplifies state management and data flow within applications. This new model is more intuitive, reducing boilerplate code and making it easier to manage complex state interactions. It also improves performance by optimizing change detection mechanisms.
2. Standalone components
One of the most anticipated features in Angular 18 is the introduction of standalone components. This allows developers to create components that do not rely on Angular modules. It makes them more modular and easier to reuse across different parts of an application or across different projects. Standalone components can significantly reduce the overhead associated with module management.
3. Improved build performance
Build performance has always been a critical aspect of Angular’s development workflow. Angular 18 includes a range of optimizations that reduce build times, particularly for large projects. Improvements in the Angular CLI, along with better caching mechanisms and incremental compilation, contribute to faster builds and more efficient development cycles.
4. Advanced template type checking
This improvement helps developers catch errors early in the development process, reduce debugging time and increase code reliability. The advanced type checking now supports more complex type scenarios, making Angular applications safer and more predictable.
5. ESM (ECMAScript Module) support
Angular 18 fully embraces ECMAScript Modules (ESM), aligning with modern JavaScript standards. ESM support ensures better compatibility with other modern libraries and tools, thus leading to more efficient code splitting and loading. This results in faster initial load times and a smoother user experience.
6. Component-level state management
State management in Angular has been traditionally handled using services and global state libraries like NgRx. With Angular 18, developers have the option to manage the state at the component level more effectively. This feature simplifies state management for small to medium-sized applications, making it easier to reason about state changes and interactions within individual components.
@Component({ selector: 'app-counter', template: ` <button(click)="increment()">Increment</button> <p>Count: {{ count }}</p> `, }) @ComponentState() export class CounterComponent { count = 0; increment() { this.count++; } }
7. Improved developer tooling
Angular 18 comes with significant improvements to developer tooling, including enhanced support in Angular DevTools. These updates provide better insights into application performance, dependency management, and state changes. The improved tooling makes it easier for developers to debug and optimize their applications.
Suggested: Learn the key differences between MERN and MEAN stack development!
8. Enhanced angular material and CDK
The Angular Material library and Component Dev Kit (CDK) have received updates to align with Angular 18’s new features. These updates include new components, improved accessibility features, and performance optimizations. The CDK enhancements make it easier to create custom components with advanced interactions and behaviors.
9. Server-side rendering (SSR) enhancements
Server-Side rendering in Angular 18 has been optimized for better performance and ease of integration. These enhancements include improved pre-rendering capabilities, faster server-side hydration, and better support for Angular Universal. SSR improvements help in reducing Time to Interactive (TTI) and improving the overall user experience, especially on slower networks.
10. Better internationalization (i18n) support
Internationalization support in Angular 18 has been refined to make it easier to localize applications. New APIs and tooling improvements streamline the process of translating and managing different language versions of an application. This is particularly beneficial for developers working on applications targeted at a global audience.
11. Accessibility improvements
Accessibility continues to be a priority in Angular 18, with several enhancements aimed at making applications more accessible out of the box. New directives and components are introduced to ensure better compliance with accessibility standards, making it easier for developers to create inclusive web applications.
12. Default content in ng-content
Angular 18 allows default content within the ng-content tag. It enhances component flexibility and provides fallback content when no projection is provided.
13. Route redirects with functions
Angular 18 introduces a new feature that allows developers to manage redirects using functions instead of plain strings. This flexibility enhances routing capabilities. To leverage these new features effectively, consider partnering with a professional Angularjs development company to enhance your project’s capabilities.
const routes: Routes = [ { path: 'page1', redirectTo: (url) => '/page2', pathMatch: 'full' } ];
The function can return either a string or an UrlTree, which captures URL information.
14. New RedirectCommand class
Angular 18 introduces the RedirectCommand class to manage NavigationExtras. Developers can use this class to handle complex navigation patterns with Guards and Resolvers.
const route: Route = { path: 'page1', component: PageComponent, canActivate: [ () => { const router: Router = inject(Router); const urlTree: UrlTree = router.parseUrl('./page2'); return new RedirectCommand(urlTree, { skipLocationChange: true }); }, ], };
15. Zoneless applications
Angular aims to incorporate signals into applications without relying on zone.js. This optimization improves performance and navigation behavior.
Suggested: Power your web and SaaS apps with the best frameworks in 2024
16. TypeScript 4.7 support
Angular 18 includes support for TypeScript 4.7, allowing developers to leverage the latest TypeScript features and improvements. These features include:
Template literal types: Give developers the ability to precisely define template types and detect errors at an early stage.
Better readonly support: Offers a safer and more reliable method of using the readonly keyword.
New import types: Promote more organization and modularity in the code.
17. Improved performance with Ivy
Ivy, Angular’s new rendering engine, continues to enhance performance and bundle size. Its enhanced tree shaking capabilities reduce the bundle size by removing unused code, leading to smaller production bundles and faster load times. These optimizations will result in:
Faster startup times
Smaller bundle sizes
Better overall performance
18. Enhanced CLI commands
Angular CLI commands receive updates for a better developer experience. New commands include ng generate component with automatic routing setup and ng lint with improved rule configuration.
19. WebAssembly support
Angular 18 allows developers to use WebAssembly modules directly in components, opening up possibilities for high-performance computations and integrations with existing WebAssembly libraries.
20. Improved AOT compilation
Ahead-of-Time (AOT) compilation gets further optimizations, resulting in faster startup times. Smaller generated code and improved performance are notable benefits.
Here are some bonus Angular 18 features:
21. New @angular/localize package
Angular 18 introduces the @angular/localize package for internationalization (i18n) and localization. Developers can easily extract and translate strings in their applications.
22. Enhanced router guards
Angular 18 enhances router guards with additional lifecycle hooks. Developers can now handle scenarios like route activation and deactivation more effectively.
23. Improved error handling
Error messages in Angular 18 are more descriptive and actionable, helping developers quickly identify and resolve issues during development.
Suggested: Discover the differences between full stack and MEAN stack developers!
Conclusion
Angular 18 represents a significant step forward in the evolution of this powerful web application framework. With its enhanced reactivity model, standalone components, improved build performance, advanced template type checking, and full ESM support, Angular 18 offers a robust set of tools and features that cater to modern web development needs.
For developers, the improvements in developer tooling, server-side rendering, internationalization, and accessibility support mean that creating high-quality, performant, and inclusive applications is more achievable than ever. Angular 18 not only addresses existing challenges but also sets the stage for future innovations in web development.
As you explore Angular 18, take advantage of the updated documentation and guides to familiarize yourself with the new features and best practices. Whether you are building a small application or a large-scale enterprise solution, Angular 18 provides the foundation and tools necessary to succeed in today’s fast-paced web development landscape.
Originally published at softwebsolutions on May 23, 2024.
1 note · View note
excellencetecchnology · 1 year ago
Text
JavaScript Mastery: Unlocking the Power of The Definitive Guide
Tumblr media
JavaScript stands as the cornerstone of modern web development, empowering developers to create interactive and dynamic experiences on the web. For those looking to delve deep into JavaScript's intricacies and master its capabilities, "JavaScript: The Definitive Guide" serves as an indispensable resource. Authored by David Flanagan, this comprehensive guide is revered for its depth, clarity, and practical insights into JavaScript programming. This article explores how "JavaScript Mastery" can transform your understanding and proficiency in JavaScript development.
Introduction to JavaScript: Foundation of Web Interactivity
JavaScript, often abbreviated as JS, was initially developed to add interactivity to static web pages. Over the years, it has evolved into a versatile language capable of handling complex tasks ranging from client-side scripting to server-side development. Understanding JavaScript's syntax, features, and best practices is crucial for anyone aspiring to excel in web development.
Why Choose "JavaScript: The Definitive Guide"?
Comprehensive Coverage of JavaScript
"JavaScript: The Definitive Guide" is renowned for its comprehensive coverage of the JavaScript language and ecosystem. The book spans from fundamental concepts like variables, data types, and control structures to advanced topics such as functional programming, asynchronous programming with promises, and modern ES6+ features. Each chapter is meticulously crafted to provide a deep dive into JavaScript's capabilities while ensuring clarity and accessibility.
Authoritative and Trusted Source
David Flanagan, the author of "JavaScript: The Definitive Guide," brings years of experience and expertise to the table. As a seasoned programmer and prolific writer, Flanagan distills complex topics into digestible explanations, making the guide suitable for both beginners and seasoned developers seeking to deepen their understanding of JavaScript.
Navigating Through "JavaScript: The Definitive Guide"
Foundational Concepts and Syntax
The guide begins with foundational JavaScript concepts, ensuring readers grasp essential syntax and programming principles. Topics such as variables, operators, functions, and control flow are explained in detail, laying a solid groundwork for more advanced discussions.
Object-Oriented Programming (OOP) in JavaScript
JavaScript's flexible nature allows developers to employ object-oriented programming paradigms effectively. Flanagan explores how JavaScript supports OOP through prototypes, constructors, inheritance, and object composition. These concepts are crucial for structuring scalable and maintainable JavaScript applications.
Modern JavaScript: ES6+ Features
"JavaScript: The Definitive Guide" doesn't just cover the basics; it dives into modern JavaScript features introduced in ECMAScript 6 (ES6) and beyond. Readers learn about arrow functions, template literals, destructuring, classes, modules, and other enhancements that streamline code readability and maintainability.
Practical Application: Projects and Exercises
Hands-On Learning Approach
One of the strengths of "JavaScript: The Definitive Guide" is its hands-on approach to learning. The book includes numerous examples, projects, and coding exercises that reinforce theoretical concepts. Readers are encouraged to apply what they've learned to real-world scenarios, honing their problem-solving skills and gaining confidence in JavaScript development.
Building Interactive Web Applications
From manipulating the DOM (Document Object Model) to handling user events and implementing AJAX (Asynchronous JavaScript and XML) for dynamic content loading, the guide equips developers with the skills needed to build responsive and interactive web applications.
Advancing Your Skills: Beyond the Basics
Performance Optimization and Best Practices
"JavaScript: The Definitive Guide" goes beyond syntax and features to address performance optimization techniques and best practices. Readers learn how to write efficient JavaScript code, avoid common pitfalls, and leverage browser tools for debugging and profiling.
Integrating JavaScript with Other Technologies
JavaScript's versatility extends beyond web browsers. The guide explores how JavaScript can be integrated with backend technologies through frameworks like. Readers gain insights into server-side JavaScript development, asynchronous programming patterns, and building RESTful APIs.
Community and Resources
Support and Collaboration
Learning JavaScript is a journey that's greatly enhanced by community support and collaboration. "JavaScript: The Definitive Guide" connects readers with a vibrant community of learners, developers, and experts. Online forums, tutorials, and additional resources complement the book's content, providing avenues for further learning and growth.
Staying Updated with Evolving Standards
JavaScript is a rapidly evolving language with new features and updates introduced regularly. "JavaScript: The Definitive Guide" helps readers stay abreast of these changes by emphasizing core concepts and principles that transcend specific language versions.
Conclusion
In conclusion, "JavaScript: The Definitive Guide" serves as more than just a reference book; it is a pathway to mastering JavaScript and unlocking its full potential in web development. David Flanagan's expertise and comprehensive approach make this guide indispensable for anyone serious about advancing their JavaScript skills. Whether you're starting your journey as a web developer or aiming to deepen your understanding of JavaScript's nuances, "JavaScript Mastery" offers a roadmap to proficiency and innovation in web development.
0 notes
tutorialwithexample · 1 year ago
Text
Level Up Your JavaScript Skills: Deep Dive into ES6 - Tutorial Edition
Tumblr media
Are you ready to take your JavaScript skills to the next level? Look no further than our ES6 Tutorial! In this beginner-friendly guide, we'll explore the wonders of ECMAScript 6, the latest version of JavaScript.
First things first, what exactly is ES6? It's simply a set of new features and syntax enhancements that make JavaScript even more powerful and easier to use. Whether you're a seasoned developer or just starting out, mastering ES6 is essential for staying relevant in today's web development landscape.
One of the most exciting features of ES6 is arrow functions. These concise and expressive functions allow you to write cleaner and more readable code. Plus, ES6 introduces let and const for variable declarations, making your code more predictable and easier to maintain.
But that's not all! With ES6, you'll also learn about template literals, enhanced object literals, destructuring assignment, default parameters, and much more. Each concept is explained in simple language with plenty of examples to help solidify your understanding.
By the end of our ES6 Tutorial, you'll have a solid foundation in modern JavaScript and be ready to tackle more advanced topics with confidence. So what are you waiting for? Let's dive into the world of ES6 and unleash your coding potential!
For more detailed guidance, visit: Tutorial and Example
0 notes
laomusicarts · 2 years ago
Text
Learning ECMAScript 6+ (ES6+)
I just finished the course “Learning ECMAScript 6+ (ES6+)” by Eve Porcello!
#lao #music #laomusic #laomusicArts #LAO #MUSIC #LAOMUSIC #LAOMUSIC_ARTS #worstteacherever #disgustinglyWhite #javascript #ecmascript
Check it out:
1 note · View note
freyayuki · 7 years ago
Text
freeCodeCamp ES6 Course Notes Part 2
As I mentioned before, now that there’s a new freeCodeCamp learning curriculum, I resolved to go through each of the lessons and finish all of them.
I was able to finish all the Responsive Web Design courses including all the projects. Check out this post for more info about these projects.
Check out the following articles for the notes I took while going through the course:
Flexbox Notes
CSS Grid Notes
Now that I’m done with the Responsive Web Design Certification course, the next course is the Javascript Algorithms And Data Structures Certification course.
The first part of that course is Basic JavaScript. Check out the notes I took while going through that course:
Part 1
Part 2
Part 3
The second part of the JavaScript course is the ES6 or ECMAScript 6 course. This is part 2 of the notes I took while going through said course. You can find part 1 here.
You can find the ES6 or ECMAScript 6 course here: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6
Use Destructuring Assignment to Pass an Object as a Function's Parameters
You can destructure the object in a function argument itself.
Tumblr media
var harryPotter = {  name: "Harry Potter",  age: 1,  address: "Godric's Hollow",  livingWith: ["James", "Lily"],  godfather: "Sirius Black",  status: "Boy-Who-Lived",  country: "England" }; var updateInfo = (function() {  "use strict";  return function updateInfo({name, age, address, livingWith}) {    harryPotter.age = 11;    harryPotter.address = "4 Privet Drive";    harryPotter.livingWith = ["Vernon", "Petunia", "Dudley"];    return `${name} is now ${harryPotter.age}. He lives in ${harryPotter.address} with his relatives: ${harryPotter.livingWith}.`  }; })(); console.log(harryPotter); //returns the harryPotter object console.log(updateInfo(harryPotter)); //returns Harry Potter is now 11. He lives in 4 Privet Drive with his relatives: Vernon,Petunia,Dudley.
Use destructuring assignment within the argument to the function half to send only max and min inside the function.
const stats = {  max: 56.78,  standard_deviation: 4.34,  median: 34.54,  mode: 23.87,  min: -0.75,  average: 35.85 }; const half = (function() {  "use strict";  return function half({max, min}) {    return (stats.max + stats.min) / 2.0;  }; })(); console.log(stats); // should be object console.log(half(stats)); // should be 28.015
Create Strings using Template Literals
template literal - “special type of string that makes creating complex strings easier.”
Template literals allow you to create multi-line strings and to use string interpolation features to create strings.
const siriusBlack = {  firstName: "Sirius",  middleName: "Orion",  lastName: "Black",  bloodStatus: "Pureblood",  brother: "Regulus",  cousins: ["Bellatrix", "Andromeda", "Narcissa"],  birthday: "3 November, 1959",  nickname: "Padfoot",  father: "Orion",  mother: "Walburga" }; // Template literal with multi-line and string interpolation const siriusInfo = `Harry Potter's godfather is ${siriusBlack.firstName} ${siriusBlack.middleName} ${siriusBlack.lastName}. He is a ${siriusBlack.bloodStatus} from the Noble and Most Ancient House of ${siriusBlack.lastName}. He was born on ${siriusBlack.birthday} to ${siriusBlack.father} and ${siriusBlack.mother} ${siriusBlack.lastName}. He has a younger brother named ${siriusBlack.brother}. He has 3 cousins: ${siriusBlack.cousins}. His friends called him ${siriusBlack.nickname}.`; console.log(siriusInfo); Harry Potter's godfather is Sirius Orion Black. He is a Pureblood from the Noble and Most Ancient House of Black. He was born on 3 November, 1959 to Orion and Walburga Black. He has a younger brother named Regulus. He has 3 cousins: Bellatrix,Andromeda,Narcissa. His friends called him Padfoot.
The example above uses  “backticks (`), not quotes ('or "), to wrap the string.”
“The string is multi-line, both in the code and the output” without having to insert \n within strings.
The ${variable}syntax used above is a placeholder. Basically, you won't have to use concatenation with the +operator anymore. To add variables to strings, you just drop the variable in a template string and wrap it with ${and }. Similarly, you can include other expressions in your string literal, for example ${a + b}.
Use template literal syntax with backticks to display each entry of the result object's failure array. Each entry should be wrapped inside an li element with the class attribute text-warning, and listed within the resultDisplayArray.
const result = {  success: ["max-length", "no-amd", "prefer-arrow-functions"],  failure: ["no-var", "var-on-top", "linebreak"],  skipped: ["id-blacklist", "no-dup-keys"] }; function makeList(arr) {  "use strict";  const resultDisplayArray = [`<li class="text-warning">${arr[0]}</li>`, `<li class="text-warning">${arr[1]}</li>`, `<li class="text-warning">${arr[2]}</li>`];  return resultDisplayArray; } /** * makeList(result.failure) should return: * [ `<li class="text-warning">no-var</li>`, *   `<li class="text-warning">var-on-top</li>`, *   `<li class="text-warning">linebreak</li>` ] **/ const resultDisplayArray = makeList(result.failure);
Alternative solution: use map function
const result = {  success: ["max-length", "no-amd", "prefer-arrow-functions"],  failure: ["no-var", "var-on-top", "linebreak"],  skipped: ["id-blacklist", "no-dup-keys"] }; function makeList(arr) {  "use strict";  const resultDisplayArray = arr.map(item => `<li class="text-warning">${item}</li>`);  return resultDisplayArray; } /** * makeList(result.failure) should return: * [ `<li class="text-warning">no-var</li>`, *   `<li class="text-warning">var-on-top</li>`, *   `<li class="text-warning">linebreak</li>` ] **/ const resultDisplayArray = makeList(result.failure);
var hpGroups = {  marauders: ["Sirius", "James", "Peter", "Remus"],  goldenTrio: ["Harry", "Ron", "Hermione"],  hogwartsFounders: ["Helga", "Rowena", "Salazar", "Godric"] }; var hpList = (list) => {  "use strict";  var results = list.map(hp => `<li class="hp-info">${hp}</li> `);  return results; } console.log(hpList(hpGroups.marauders)); //returns <li class="hp-info">Sirius</li> ,<li class="hp-info">James</li> ,<li class="hp-info">Peter</li> ,<li class="hp-info">Remus</li> console.log(hpList(hpGroups.hogwartsFounders)); //returns <li class="hp-info">Helga</li> ,<li class="hp-info">Rowena</li> ,<li class="hp-info">Salazar</li> ,<li class="hp-info">Godric</li>  
Write Concise Object Literal Declarations Using Simple Fields
Tumblr media
var hpChara = (firstName, lastName, gender, hogwartsHouse) => {  "use strict";  return{    firstName, lastName, gender, hogwartsHouse  }; }; console.log(hpChara("Hermione", "Granger", "Female", "Gryffindor")); {firstName: "Hermione", lastName: "Granger", gender: "Female", hogwartsHouse: "Gryffindor"} console.log(hpChara("Luna", "Lovegood", "Female", "Ravenclaw")); {firstName: "Luna", lastName: "Lovegood", gender: "Female", hogwartsHouse: "Ravenclaw"} console.log(hpChara("Draco", "Malfoy", "Male", "Slytherin")); {firstName: "Draco", lastName: "Malfoy", gender: "Male", hogwartsHouse: "Slytherin"}
Write Concise Declarative Functions with ES6
Tumblr media
Refactor the function setGear inside the object bicycle to use the shorthand syntax described above.
const bicycle = {  gear: 2,  setGear(newGear) {    "use strict";    this.gear = newGear;  } }; bicycle.setGear(3); console.log(bicycle.gear); bicycle.setGear(48); //changes gear value to 48
const astoriaInfo = {  fullName: "Astoria Greengrass",  setInfo(newInfo) {    "use strict";    this.fullName = newInfo;  } }; astoriaInfo.setInfo("Astoria Malfoy"); console.log(astoriaInfo.fullName); //returns Astoria Malfoy
Use class Syntax to Define a Constructor Function
keyword class - new syntax to help create objects
Tumblr media
function makeHorcrux() {  "use strict";  class Horcrux {    constructor(item) {      this.item = item;    }  }  return Horcrux; } const Horcrux = makeHorcrux(); const ravenclawsDiadem = new Horcrux("Ravenclaw's Diadem"); console.log(ravenclawsDiadem.item); //returns Ravenclaw's Diadem const hufflepuffsCup = new Horcrux("Hufflepuff's Cup"); console.log(hufflepuffsCup.item); //returns Hufflepuff's Cup
Use class keyword and write a proper constructor to create the Vegetable class.
The Vegetable lets you create a vegetable object, with a property name, to be passed to constructor.
function makeClass() {  "use strict";  class Vegetable {    constructor(name) {      this.name = name;    }  }  return Vegetable; } const Vegetable = makeClass(); const carrot = new Vegetable('carrot'); console.log(carrot.name); //returns 'carrot'
function makeWands() {  "use strict";  class HPWands {    constructor(wood, core) {      this.wood = wood;      this.core = core;    }  }  return HPWands; } const HPWands = makeWands(); const harrysWand = new HPWands("Holly", "Phoenix Feather"); console.log(`Harry Potter has a ${harrysWand.wood} and ${harrysWand.core} wand.`); //returns Harry Potter has a Holly and Phoenix Feather wand. const fleursWand = new HPWands("Rosewood", "Veela Hair"); console.log(`Fleur Delacour has a ${fleursWand.wood} and ${fleursWand.core} wand.`); //returns Fleur Delacour has a Rosewood and Veela Hair wand.
Use getters and setters to Control Access to an Object
You can obtain values from an object, and set a value of a property within an object.
Getter functions are meant to simply return (get) the value of an object's private variable to the user without the user directly accessing the private variable.
Setter functions are meant to modify (set) the value of an object's private variable based on the value passed into the setter function. This change could involve calculations, or even overwriting the previous value completely.
Tumblr media
class Book {  constructor(title) {    this._title = title;  }  //getter function  get bookTitle() {    return this._title; //returns or gets the title of the book  }  //setter function  set bookTitle(updatedTitle) {    this._title = updatedTitle; //set or update the title of the book  } } const hp = new Book("Harry Potter and the Sorcerer's Stone"); console.log(hp.bookTitle); //returns Harry Potter and the Sorcerer's Stone hp.bookTitle = "Harry Potter and the Philosopher's Stone"; //updates or changes the book title console.log(hp._title); //returns Harry Potter and the Philosopher's Stone
class StudentInfo {  constructor(name, age) {    this.name = name;    this.age = age;  }  //getter function  get student() {    return `The student's name is ${this.name} and their age is ${this.age}.` ;  }  //setter function  set student(updatedInfo) {    this.age = updatedInfo;    this.name = updatedInfo;  } } const hermioneInfo = new StudentInfo("Hermione Granger", 11); console.log(hermioneInfo.student); //returns The student's name is Hermione Granger and their age is 11. hermioneInfo.age = 17; hermioneInfo.name = "Hermione Weasley"; console.log(hermioneInfo.student); //returns The student's name is Hermione Weasley and their age is 17.
class Wands {  constructor(name, wood, core) {    this.name = name;    this.wood = wood;    this.core = core;  }  //getter function  get wand() {    return `${this.name} has a ${this.core} and ${this.wood} wand.`;  }  //setter function  set wand(updatedInfo) {    this.name = updatedInfo;    this.wood = updatedInfo;    this.core = updatedInfo;  } } const ronsWand = new Wands("Ron Weasley", "Unicorn Hair", "Ash"); console.log(ronsWand.wand); //returns Ron Weasley has a Unicorn Hair and Ash wand. ronsWand.wood = "Willow"; console.log(ronsWand.wand); //returns Ron Weasley has a Unicorn Hair and Willow wand. ronsWand.wood = "Chestnut"; ronsWand.core = "Dragon Hearstring"; console.log(ronsWand.wand); //returns Ron Weasley has a Dragon Heartstring and Chestnut wand.
Use class keyword to create a Thermostat class. The constructor accepts Fahrenheit temperature.
Now create getter and setter in the class, to obtain the temperature in Celsius scale.
Remember that C = 5/9 * (F - 32)and F = C * 9.0 / 5 + 32, where F is the value of temperature in Fahrenheit scale, and C is the value of the same temperature in Celsius scale
When you implement this, you would be tracking the temperature inside the class in one scale - either Fahrenheit or Celsius.
This is the power of getter or setter - you are creating an API for another user, who would get the correct result, no matter which one you track.
In other words, you are abstracting implementation details from the consumer.
function makeClass() {  "use strict";  class Thermostat {    constructor(temperature) {      this.temperature = temperature;    }    //getter function    get celsius() {      return this.temperature;    }    //setter function    set celsius(updatedTemp) {      this.celsius = updatedTemp;    }  }  return Thermostat; } const Thermostat = makeClass(); const thermos = new Thermostat(76); // setting in Fahrenheit scale let temp = thermos.temperature; // 24.44 in C thermos.temperature = 26; temp = thermos.temperature; // 26 in C
Differences Between import and require
the function require()would be used to import the functions and code in external files and modules. While handy, this presents a problem: some files and modules are rather large, and you may only need certain code from those external resources.
ES6 gives us a very handy tool known as import. With it, we can choose which parts of a module or file to load into a given file, saving time and memory.
Tumblr media
For more info, refer to this: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/understand-the-differences-between-import-and-require
Add the appropriate import statement that will allow the current file to use the capitalizeString function. The file where this function lives is called "string_functions", and it is in the same directory as the current file.
"use strict"; capitalizeString("hello!"); import { capitalizeString } from "string_functions"
Use export to Reuse a Code Block
import - “can be leveraged to import small amounts of code from large files.”
export - “When we want some code - a function, or a variable - to be usable in another file, we must export it in order to import it into another file.”  
Like import, export is a non-browser feature.
named export - use this to “import any code we export into another file with the import syntax”. Also, this allows you to “make multiple functions and variables available for use in other files”
Tumblr media
//export the two variables export const black = "sirius"; export const potter = "james";
Use * to Import Everything from a File
Tumblr media
The code below requires the contents of a file, "capitalize_strings", found in the same directory as it, imported. Add the appropriate import *statement to the top of the file, using the object provided.
"use strict"; import * as capitalizeStrings from "capitalize_strings";
//another example: import * as gobletOfFire from "triwizard_tournament"; import * as voldemortsHorcruxes from "founders_items";
Create an Export Fallback with export default
export default - another export syntax. “Usually you will use this syntax if only one value is being exported from a file. It is also used to create a fallback value for a file or module.”
Tumblr media
"use strict"; //The following function should be the fallback value for the module //function subtract(x,y) {return x - y;} export default function subtract(x,y) {return x - y;}
Import a Default Export
To import a default export, you need to use a different import syntax.
Tumblr media
"use strict"; //import the default export, subtract, from the file "math_functions", found in the same directory as this file. import subtract from "math_functions"; subtract(7,4);
0 notes
snetzweb · 4 years ago
Text
Web Development Roadmap
To start a career in the web development field, you need to choose either front-end web development or back-end web development and if you want to be a full-stack developer you can choose both. Here we will discuss both paths. First, we will talk about what things you should learn and use to go on either path.
Here are some core technologies and tools you need to learn for both frontend and backend roadmap tasks.
Git -
One of the most popular version control systems. It's not possible to live without Git anymore. Git is a software for tracking changes in any set of files, usually used for coordinating work among programmers. It’s goals include speed, data integrity and non-linear workflows.
SSH -
SSH stands for Secure Shell. It is a Cryptographic Network Protocol for operating network services securely over an unsecured network. Typically applications include Remote Command Line, Login and Remote Command Execution. Every network service can be secured with SSH.
It is a popular networking concept every web developer should know.
HTTP/HTTPS -
HTTP stands for Hypertext Transfer Protocol and HTTPS stands for Hypertext Transfer Protocol Secure.
Hypertext Transfer Protocol Secure is an Extension of Hypertext Transfer Protocol. It is widely used over the Internet. For Secure Communication over a computer network, HTTPS is a good way to communicate. HTTP Protocol is the Backbone of the web, and to be a Web Developer you should have good knowledge of both HTTP and HTTPS.
Linux Command - Basic Terminal Uses -
Linux command is the utility of the Linux Operating System. All basic and advanced tasks can be done by executing commands. The commands are executed on the Linux Terminal. The terminal is a Command Line Interface. It is used to interact with the system, it is similar to Command Prompt in Windows.
Not just a Web Developer but for any Programmer, Command Line is a very important factor.
Data Structures & Algorithms -
A Data Structure is a named location which can be used to store and organize data. An Algorithm is a collection of steps which help you to solve a problem. Learning Data Structure and Algorithms allows us to write efficient and optimized computer programs
These are the building blocks for every program and better knowledge of data structure and algorithm. It is vital for your next job or doing well at your current job..
Character Encoding -
If you are creating global applications that show information in multiple languages, across the world then you should have a good knowledge of character encoding.
Character Encoding is used in Computing, Data Storage and Data Transmission to represent a collection of characters by some kind of encoding system. This technique assigns a number to each character for digital representation.
Github -
There is no doubt that every developer or programmer uses Github and Git for getting code information and give some mock tests to check the performance in coding.
Both Git and Github are the standard terms in code repositories.
Github is a provider of internet hosting for software development and version control using Git. It offers the Distributed Version Control and Source Code management functionality.
Now we will discuss both the roadmaps, step by step.
Frontend Developer Roadmap -
If you want to become a Frontend Developer then you should have knowledge in some coding technologies.
In the starting phase, you should have knowledge about some basics of HTML, CSS and JavaScript.
In HTML you should know about the basics of html, semantic html, basic seo and accessibility.
In CSS you should know about the basics of css, making layout, media queries and also CSS3. You should know roots, positioning, display, box model, css grid and flex box.
In JavaScript, you should have a knowledge about syntax and basic constructs, learn dom manipulation, learn fetch api, ajax, ecmascript 6 and modular javascript.
Then you need to start learning about Package Managers, in this you can learn npm and yarn. npm is the latest technology, but still behind yarn in some features. You can select one of them.
Then you have to learn about CSS Preprocessors, which should be SASS and PostCSS.
You can learn about CSS Frameworks, in this you should know about Bootstrap 4.
You can start learning about CSS Architecture, with modern frontend frameworks, there is more push towards CSS in JS methodologies.
Now you can build tools, Task Runners, Module Bundlers, Linters and Formatters. In task runners, you can use npm scripts. In module bundlers, you can use webpack and rollers.
After completing all these steps you need to choose a Framework, it should be Reactjs, Angular and Vue.js. Then use CSS in JS and then test your apps.
Web Development Basics -
It's pretty apparent that if you want to become a web developer, then you should know the basics of the internet, web applications, protocols like http. In general you have knowledge about web development.
HTML and CSS -
HTML and CSS are the backbones of any website, html provides the structure and css provides the style and helps them to look better. If you want to become a serious frontend developer then you must master these two.
JavaScript -
Just like the four pillars of object oriented programming, encapsulation, abstraction, polymorphism and inheritance. Web Development has three pillars, which are HTML, CSS and JavaScript.
HTML and CSS provide structure and style but Javascript makes them alive by adding Interactiveness.
TypeScript -
Just like in programming, we should know about C and C++, the same as TypeScript, which is considered as JavaScript++.
TypeScript is also a programming language developed by Microsoft and also maintained by Microsoft. It is a superset of JavaScript. It is designed for the development of large applications.
Angular -
Angular is a web application framework. It is a typescript based free and open source framework. It is developed by the Angular Team of Google. Angular is an enhanced form of AngularJS, it is completely rewrite.
In the starting phase you should have knowledge about HTML, CSS and JavaScript. But these days, most of them work on Angular, Vue.js, Reactjs and Typescript.
They provide short and simple code which consumes low storage.
Reactjs -
Like Angular, Reactjs is also a very popular library to develop web applications. Reactjs is developed and maintained by Facebook Team. Most people work on reactjs instead of php and other programming languages.
Reactjs is an enhanced form of PHP and we can also include HTML, CSS and JavaScript.
Backend Web Developer Roadmap -
To become a backend web developer, you need to know about some languages.
So the first step is to pick a language.
It should be Functional Language and Scripting Language.
In functional language you need to learn about Java and .Net and in Scripting language you need to learn about Python, Ruby, PHP, Node.js and Typescript.
After learning all these languages, you need to start doing practice, as a beginner you need to do the practice.
Implement those commands you have learned. Learn about the Package manager and start implementing this. Learn about Testing and Bug Fixing.
Start knowing about Relational Database and Framework. You can learn MongoDB Database, it is enough to know about databases and uses of databases. Then start gaining knowledge of Web Server like Apache.
Node.js -
Same as reactjs, node.js is mostly used by maximum web developers. Like reactjs, node.js allows you to make complete web applications using a single language which is Node.js.
Java -
Mostly in the starting phase, people start learning about java. And almost all made their first application using java. Java is a very old language but its popularity is not gone till now like C. Java provides 99% features of object-oriented programming.
Python -
Python is a trending Language, you should have a focus on python. You can make your career bright by learning Python. If you want to develop the back-end code using python then you can use Django. It is a Full Stack Web Development Framework for Python Programmers.
8 notes · View notes
yaseminbayhan · 5 years ago
Text
instagram
Just starting to learn even with the instagram.
JavaScript:
JavaScript is a programming language that conforms to the ECMAScript specification. It is a high-level scripting language introduced by Netscape to be run on the client-side of the web browser. It can insert dynamic text into HTML.JavaScript is also known as browser’s language.
HTML:
HTML (HyperText Markup Language) is the most basic building block of the Web. It defines the meaning and structure of web content. It is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages.
Let’s see the difference between JavaScript and HTML:
S.NO. JAVASCRIPT HTML
1 JavaScript is a high-level scripting language introduced by Netscape to be run on the client-side of the web browser. HTML is the most basic building block of the Web. It defines the meaning and structure of web content.
2 JavaScript is an advanced programming language that makes web pages more interactive and dynamic. HTML is a standard markup language that provides the primary structure of a website.
3 JavaScript simply adds dynamic content to websites to make them look good. HTML work on the look of the website without the interactive effects and all.
4 It manipulates content to create dynamic web pages HTML pages are static which means the content cannot be changed.
5 It adds interactivity to web pages to make them look good. It defines the basic structure of a web page.
6 JavaScript is an advanced programming language used to create dynamic web pages. HTML is rendered from all server – side which is different from client-side scripting.
7 JavaScript is not cross-browser compatible.
HTML is cross-browser compatible. I think that issues like this should be taken seriously while programming. Because this is a newly learned and evolving language. That's why we, as writers, have to read and learn new things every moment.
2 notes · View notes
w3villatechnologies · 5 years ago
Text
A Small Guide to Choose the Right NodeJs Framework for Web Development
Either you are at developer end or at client-end, you need to be well-aware of the various frameworks that nodejs development services offer to make the right choice for web development. Although choosing the right framework can be tricky, we would like to list these frameworks for your better understanding.
Tumblr media
1. AdonisJs
Apps built with NodeJS & Adonis perform faster across various platforms and operating systems. Its stable eco-system helps developers to choose a business-friendly package and write a server-side web application. Adonis creates efficient SQL-queries as they are easy to learn and implement.
2. Express.js
For fast, minimalist, and non-opinionated framework Express.js can help servers and routes to be easily managed. It offers the ability to develop lightweight apps to carry out multitasks seamlessly. Express.js acts as a bridge between front-end & database, for users to send and receive a request to configure routes. The best thing is that developers with basic knowledge would find it easy to learn and it also offers customizable solutions. Express.js is a very useful framework under any nodejs development services.
3. Meteor.js
Its a full-stack JS platform for developers to build cutting-edge applications for web and mobile with the ability to add real-time updates. What sets this framework apart from others is that the development and real-time updates can run simultaneously. It offers a simple process by providing an entire tier of the application written in the single JavaScript language.
4. Nest.js
To make server-side web applications more efficient, scalable, and fast, NestJS is the right option to work with NodeJS. It combines elements like OOP, FP, FRP to provide an amazing architecture. It has an array of features, enabled through Nest CLI.
5. Sails.js
Build high-speed and scalable applications with Sails.js as it uses a data-driven API that offers plenty of service-oriented architecture. Its equipped with ORM to make itself compatible with all databases. It supports many adapters like MYSQL, MongoDB, PostgreSQL, etc. It also includes automated generators, it can work easily with other languages like React, Angular, Backbone, iOS/Objective C, etc.
6. Koa.js
Koa.js is the next-gen framework as unlike others it uses ECMAScript (ES6) methodologies. Developers can find the error faster and resolve them efficiently. Koa.js offers futuristic options, it has component-based building blocks, and very modular.
7. LoopBack.js
Build dynamic applications with the help of CLI & API explorer using the LoopBack.js framework. It can conveniently be used with REST and other databases like Postgres, MYSQL, MongoDB, Oracle, etc. You can also build a dynamic application using schema, developers can connect devices and browsers to data and services. It runs on both on-premises and cloud servers. This is also one of the favorable frameworks when it comes to the Node.js application development service.
8. Hapi.js
Hapi.js helps the server data to be implemented by bridging the gap between server-side and client-side. It can create a server on a specific IP which is possible through the onPreHandler feature. Hapi.js has good command over request handling, it has rich functions to build web servers, other features are also included like cashing, authentication, and input validation. It offers API references with a detailed view.
9. Derby.js
This framework allows developers to add customized codes to deliver fully scalable web applications. Derby.js uses native DOM methodologies to render templates on the server. The framework is used by a major nodejs development company.
10. Total.js
Total.js is used to build fast and customized web apps and eCommerce apps, REST service apps, IoT apps, etc. It offers faster developments with a low maintenance cost that is both advantageous to clients and developers. Web Application Development Company has been using Total.js for long to deliver scalable apps.
11. Socket.io
Socket.io in Node.js framework enables real-time, bidirectional, and event-based communication. It runs on cross-platforms like iOS, Mac, Windows devices, and browsers. You can create a chat app in just a few lines of code, provides real-time analytics, binary streaming, document collaboration, etc.
We hope this will help you a little to understand the difference between these Node.JS frameworks. If you would like to seek further information regarding nodejs development services, you can get in touch with W3villa technologies, for consulting services and custom web application development services.
1 note · View note
karanchadda · 2 years ago
Text
skills a React.js developer must-have!
1. HTML and CSS
HTML and CSS are essential if you want to hire a React front-end developer. 
The candidate's proficiency with these client-side technologies and significant react developer tools provides insight into their capacity to design and work with extremely intuitive, value-rich user experiences (UIs).
Given that UIs currently play a large role in determining how valuable and high-quality an application is deemed to be, the skill set of a React JS developer might indirectly impact the same.
2. Fundamentals of JavaScript
One of the key competencies needed for ReactJS developers in JavaScript. 
As a result, you must evaluate their knowledge of JavaScript fundamentals, including code organization, variables, data types, operators, loops, switch statements, objects, primitives, boolean, arrays, and more. 
Giving these ideas the weight they deserve is essential since they apply to both writing JavaScript and writing code for ReactJS web development. 
As a result, if their foundational understanding is strong, so would their capacity as a React JS developer.
3. JavaScript ES6
A good grasp of ES6 must be added to a React developer's skill set, in addition to a working knowledge of JavaScript's fundamentals (ECMAScript 2015 or ECMAScript 6). 
The developer can create and manage web applications in accordance with your needs, thanks to this more recent version of JavaScript.
4. JavaScript XML(JSX)
Since we're already discussing how important it is for React developers to have access to JavaScript, JSX also deserves special consideration. 
JSX, a JavaScript syntax extension, makes coding more ergonomic. Developers proficient in JSX and ReactJS can easily code and include HTML/XML elements in React. 
link -
0 notes
aditioffpage1 · 2 years ago
Text
Introduction to Different Types of JavaScript for Web Applications
Are you looking to learn more about the different types of JavaScript? As a web developer, understanding the various options available for JavaScript is vital for success in your profession. In this article, we will provide an introduction to the different types of JavaScript, including client-side, server side, frameworks, libraries, trans pilers, poly-fills, syntax parsers and code optimizers. 
Client-side JavaScript (also known as frontend JavaScript) is used to create interactive webpages that are viewable on modern web browsers. It allows developers to add interactivity and dynamic content to their websites. Additionally, it can be used to manipulate HTML and CSS elements which provides users with an improved experience when they interact with these elements on a webpage. 
Server-side JavaScript (also known as backend JavaScript) is used primarily for server-side applications such as creating databases or processing data. It can also be used to build websites and APIs that require data from the server or database. Unlike frontend JavaScript which runs on the user's browser, server-side JavaScript is executed on the server and then sent to the user's browser when required.
Read on about DataTrained – The Best Data Science Institute in India
Frameworks are prewritten code that provide developers with a structure for building applications quickly and efficiently. Popular frameworks include ReactJS and NodeJS which both have extensive libraries of prebuilt components that make development faster and easier. They also allow developers to build complex applications from smaller components instead of having to write code from scratch each time. 
Libraries are collections of code written by others that can be incorporated into your own projects and applications. Popular library examples include jQuery and Dojo Toolkit which help developers with many aspects of coding.
Mastering Different Types of Java-script for Web Applications
Writing web applications in JavaScript has become immensely popular in recent years. With the everchanging and expanding world of technology, understanding the different types of JavaScript is essential for developers to successfully create and maintain web applications. To help you master different types of JavaScript for web applications, here’s a comprehensive guide on the various variations of JavaScript, frameworks, runtime environments, query languages, and debugging techniques you should be aware of. 
JavaScript Variations
When it comes to JavaScript variations, there are 3 main types: frontend JavaScript, backend JavaScript, and ES6 features. Frontend JavaScript is used to create interactive elements on a website by writing code that alters the website’s user interface. Backend JavaScript is used to power the logic behind a website’s server-side components. Lastly, ES6 (ECMAScript 6) introduces new syntax elements and also includes some features that make it easier to write complicated code such as classes, constants, arrow functions etc. 
Frameworks 
When developing web applications with JavaScript, frameworks like React or Vue can simplify complex tasks when developing frontend interfaces or React Native for mobile apps. Angular provides many useful tools for structuring standard enterprise projects which makes it a popular framework choice for many teams. With tools like React Hooks and Context API making state management easier than ever before. 
Also read about the Best Data Analytics Courses in Chennai 
Runtime Environment & Query Language 
The Node.js runtime environment makes it possible to run JavaScript outside of the browser—meaning that you can use the same language across your entire project rather than mixing languages (such as PHP/Python). Additionally Graph QL is an opensource query language that allows different software systems to interact with one another without relying on traditional REST.
0 notes
digitalrarun · 3 years ago
Text
Why React Js is popular?
ReactJs is a JavaScript library which Facebook develops.
The main advantage of using ReactJs is that React is working on Virtual Dom. But Other Library works on Real dom which makes an application slow as compared to an application create in ReactJs.
Things you need to Learn before ReactJs are as follow 1. First of all you need the dedication to learn new things. If you delicately learn ReactJs then you quickly learn JavaScript within 1 or 2 Months.
2. You need to learn basic HTML because JSX ( JavaScript XML ) syntax is the same as HTML.
3. If you are interested in styling and designing a website then you need to learn CSS
4. You need to learn Javascript and ES6 ( ECMAScript 6 ).
0 notes
codesolutionsstuff · 3 years ago
Text
Top 10 ES6 Features Every JavaScript Developer Must Know
Tumblr media
The most recent iteration of JavaScript was released in 2015 and is called JavaScript ES6 (also known as ECMAScript 2015 or ECMAScript 6). The programming language used by JavaScript is called ECMAScript. The guidelines for how the JavaScript programming language should operate are provided by ECMAScript. We'll go over some of the top ES6 features in this blog that you may utilize in your regular JavaScript code. - What is ES6? - Understanding ES6 Features- let and const keywords - Arrow Functions - Multi-line Strings - Default Parameters - Template Literals - Destructuring Assignment - Enhanced Object Literals - Promises - Classes - Modules - Summary
What is ES6?
The sixth major edition of the ECMAScript language specification standard is known as ES6, or ECMAScript 2015. It has become far more well-liked than the previous edition, ES5, and it defines the standard for the implementation of JavaScript. The JavaScript language has undergone considerable changes as a result of ES6. In order to make writing in JavaScript simpler and more enjoyable, it included a number of new features, including the let and const keywords, the rest and spread operators, template literals, classes, and modules. We'll talk about some of the top and most in-demand ES6 features in this article and how to use them when writing JavaScript on a regular basis. - let and const Keywords - Arrow Functions - Multi-line Strings - Default Parameters - Template Literals - Destructuring Assignment - Enhanced Object Literals - Promises - Classes - Modules
Understanding ES6 Features
1. let and const keywords : Users can define variables using the keyword "let," whereas they can define constants using the keyword "const." In the past, variables were declared by using the top-level keyword "var," which had function scope. It indicates that a variable may be utilized prior to declaration. But, the "let" variables and constants have block scope which is surrounded by curly-braces "{}" and cannot be used before declaration. let i = 10; console.log(i); //Output 10 const PI = 3.14; console.log(PI); //Output 3.14 2. Arrow Functions The Arrow Functions functionality is a part of ES6. By omitting the "function" and "return" keywords, it offers a more succinct syntax for creating function expressions. The fat arrow (=>) notation is used to define arrow functions. // Arrow function let sumOfTwoNumbers = (a, b) => a + b; console.log(sum(10, 20)); // Output 30 It is clear that the declaration of the arrow function does not contain the keywords "return" or "function." When there is precisely one parameter, we can omit the parenthesis; however, when there are zero or several parameters, we must always use them. However, we must enclose the function body in curly brackets ("{}") if it contains several expressions. In order to return the necessary value, we must also utilize the "return" statement. 3. Multi-line Strings Also available in ES6 are Multi-line Strings. Back-ticks(') are used to produce multi-line strings by users. The steps are as follows: let greeting = `Hello World, Greetings to all, Keep Learning and Practicing!` 4. Default Parameters In ES6, users can provide the default values directly in the function signature. However, with ES5, the OR operator was required. //ES6 let calculateArea = function(height = 100, width = 50) { // logic } //ES5 var calculateArea = function(height, width) { height = height || 50; width = width || 80; // logic } 5. Template Literals Very basic string templates and variable placeholders are also new features of ES6. The back-ticked string contains the syntax ${PARAMETER}, which is utilized to use the string template. let name = `My name is ${firstName} ${lastName}` 6. Destructuring Assignment One of the most used ES6 features is destructuring. An expression that makes it simple to separate off values from arrays or properties from objects into separate variables is the destructuring assignment. Destructuring assignment expressions come in two flavours: array destructuring and object destructuring. It can be applied in the ways listed below: //Array Destructuring let fruits = ; let = fruits; // Array destructuring assignment console.log(a, b); //Object Destructuring let person = {name: "Peter", age: 28}; let {name, age} = person; // Object destructuring assignment console.log(name, age); 7. Enhanced Object Literals Enhanced object literals are a feature of ES6 that make it simple to quickly build objects with properties inside curly braces. function getMobile(manufacturer, model, year) { return { manufacturer, model, year } } getMobile("Samsung", "Galaxy", "2020"); 8. Promises Promises are utilized for asynchronous execution in ES6. As shown here, we can combine promise and the arrow function. var asyncCall = new Promise((resolve, reject) => { // do something resolve(); }).then(()=> { console.log('DON!'); }) 9. Classes JavaScript has never before had classes. In ES6, classes are introduced. Classes in other object-oriented languages, such C++, Java, PHP, etc., resemble classes in ES6. But they don't operate in precisely the same manner. By employing the "extends" keyword to implement inheritance, ES6 classes make it easier to construct objects and reuse code effectively. In ES6, we can declare classes by preceding the class name with the new "class" keyword. class UserProfile { constructor(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } getName() { console.log(`The Full-Name is ${this.firstName} ${this.lastName}`); } } let obj = new UserProfile('John', 'Smith'); obj.getName(); // output: The Full-Name is John Smith 10. Modules Until recently, JavaScript lacked native support for modules. A brand-new function known as modules was added to ES6. Each module is represented by a distinct ".js" file. Variables, functions, classes, and other components can be imported or exported from or to different files and modules by using the "import" or "export" declaration in a module. export var num = 50; export function getName(fullName) { //data }; import {num, getName} from 'module'; console.log(num); // 50 Summary - This post introduced us to ECMAScript 2015, often known as ES6, which establishes the benchmark for JavaScript implementation. - The top 10 ES6 Features that make it so well-liked were also covered in this lesson. - Working with JavaScript is significantly facilitated by ES6's classes, modules, arrow functions, template literals, destructuring assignments, and many other features. Read the full article
0 notes
freyayuki · 7 years ago
Link
freeCodeCamp ES6 Course Notes Part 1 
As I mentioned before, now that there’s a new freeCodeCamp learning curriculum, I resolved to go through each of the lessons and finish all of them.
I was able to finish all the Responsive Web Design courses including all the projects. Check out this post for more info about these projects.
Check out the following articles for the notes I took while going through the course:
Flexbox Notes
CSS Grid Notes
Now that I’m done with the Responsive Web Design Certification course, the next course is the Javascript Algorithms And Data Structures Certification course.
The first part of that course is Basic JavaScript. Check out the notes I took while going through that course:
Part 1
Part 2
Part 3
The second part of the JavaScript course is the ES6 or ECMAScript 6 course. This is part 1 of the notes I took while going through said course.
Differences Between the var and let Keywords
One of the biggest problems with declaring variables with the var keyword is that you can overwrite variable declarations without an error.
var potter = "James"; var potter = "Harry"; console.log(potter); //logs "Harry"
So it’s easy to accidentally overwrite variables without meaning to.
let - new keyword introduced in ES6
let malfoy = "Lucius"; let malfoy = "Draco"; //throws an error because we're using let
Tumblr media
let harryPotter; let message; function harrysMessage() {  "use strict";  harryPotter = "Harry Potter";  message = harryPotter + " says that Voldemort is back."; } harrysMessage();
Compare Scopes of the var and let Keywords
When you declare a variable with the var keyword, it is declared globally, or locally if declared inside a function.
The let keyword behaves similarly, but with some extra features. When you declare a variable with the let keyword inside a block, statement, or expression, its scope is limited to that block, statement, or expression.
Refer to this for more info and examples: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/compare-scopes-of-the-var-and-let-keywords
function checkScope() { "use strict";  let i = "function scope";  if (true) {    let i = "block scope";    console.log("Block scope i is: ", i); //the i here returns block scope  }  console.log("Function scope i is: ", i); //the i here returns function scope  return i; } checkScope(); Block scope i is:  block scope Function scope i is:  function scope "function scope"
const keyword - has same features as let keyword. Also “variables declared using const are read-only. They are a constant value, which means that once a variable is assigned with const, it cannot be reassigned.”
Tumblr media
function bookInfo(title) {  "use strict";  const BOOK_INFO = "The " + title + " was written by J.K. Rowling.";  for (let i = 0; i < title.length; i+=2) {    console.log(BOOK_INFO);  } } bookInfo("Harry Potter series"); //returns The Harry Potter series was written by J.K. Rowling 10 times 10 The Harry Potter series was written by J.K. Rowling.
Mutate an Array Declared with const
Objects (including arrays and functions) assigned to a variable using const are still mutable. Using the const declaration only prevents reassignment of the variable identifier.
Tumblr media
const DISOWNED_BLACKS = ["Regulus", "Bellatrix", "Andromeda", "Narcissa"]; function editBlackFamily() {  "use strict";  DISOWNED_BLACKS[0] = "Sirius";  DISOWNED_BLACKS[1] = "Cedrella";  DISOWNED_BLACKS[3] = "Alphard"; } editBlackFamily(); console.log(DISOWNED_BLACKS); (4) ["Sirius", "Cedrella", "Andromeda", "Alphard"]
Use the Object.freeze function to prevent data mutation / ensure your data doesn’t change. 
Once the object is frozen, you can no longer add, update, or delete properties from it. Any attempt at changing the object will be rejected without an error.
let harrysGodfather = {  firstName: "Sirius",  lastName: "Black" }; Object.freeze(harrysGodfather); harrysGodfather.firstName = "Regulus"; //will be ignored because the Object.freeze function prevents object mutation harrysGodfather.bestFriend = "James Potter"; //will be ignored because the Object.freeze function prevents object mutation console.log(harrysGodfather); {firstName: "Sirius", lastName: "Black"}
Use Object.freeze to prevent mathematical constants from changing. 
Freeze the MATH_CONSTANTS object so that no one is able alter the value of PI, add, or delete properties .
function freezeObj() {  "use strict";  const MATH_CONSTANTS = {    PI: 3.14  };  Object.freeze(MATH_CONSTANTS);  try {    MATH_CONSTANTS.PI = 99;  } catch( ex ) {    console.log(ex);  }  return MATH_CONSTANTS.PI; } const PI = freezeObj();
Use Arrow Functions to Write Concise Anonymous Functions
Tumblr media Tumblr media
var magic = function() {  "use strict";  return new Date(); }; //Using arrow function syntax, the above can be rewritten as: const magic = () => {  "use strict";  return new Date(); };
magic(); will return the current date.
Examples of using arrow functions:
let darkLord = () => "I am Lord Voldemort"; console.log(darkLord); () => "I am Lord Voldemort"
harryPotter = () => "The Boy-Who-Lived"; () => "The Boy-Who-Lived" harryPotter () => "The Boy-Who-Lived" console.log(harryPotter()); The Boy-Who-Lived
var marauders = (name) => (name === "James Potter") ? "bullied Snape" : (name === "Sirius Black") ? "Harry's godfather" : (name === "Remus Lupin") ? "werewolf" : "traitor" //question mark is ternary (conditional) operator, same as if-else statements marauders("James Potter"); "bullied Snape" marauders("Peter Pettigrew"); "traitor" marauders("Sirius Black"); "Harry's godfather" marauders("Remus Lupin"); "werewolf"
Write Arrow Functions with Parameters
Tumblr media
//appends contents of arr2 to arr1 var myConcat = function(arr1, arr2) {  "use strict";  return arr1.concat(arr2); }; console.log(myConcat([1, 2], [3, 4, 5])); (5) [1, 2, 3, 4, 5]
//Using arrow function syntax, the above code can be rewritten as: const myConcat = (arr1, arr2) => {  "use strict";  return arr1.concat(arr2); }; console.log(myConcat([1, 2], [3, 4, 5]));
Another example:
const hogwartsHouses = (house1, house2) => {  "use strict";  return house1.concat(house2); }; console.log(hogwartsHouses(["Slytherin", "Ravenclaw"], ["Hufflepuff", "Gryffindor"])); (4) ["Slytherin", "Ravenclaw", "Hufflepuff", "Gryffindor"]
var hogwartsStudent = (name, house) => `Hi. My name is ${name}. I am a student in Hogwarts School of Witchcraft and Wizardry. My house is ${house}.` hogwartsStudent("Luna Lovegood", "Ravenclaw"); "Hi. My name is Luna Lovegood. I am a student in Hogwarts School of Witchcraft and Wizardry. My house is Ravenclaw." hogwartsStudent("Cedric Diggory", "Hufflepuff"); "Hi. My name is Cedric Diggory. I am a student in Hogwarts School of Witchcraft and Wizardry. My house is Hufflepuff."
Write Higher Order Arrow Functions
Arrow functions work really well with higher order functions, such as map(), filter(), and reduce(), that take other functions as arguments for processing collections of data.
Tumblr media
Use arrow function syntax to compute the square of only the positive integers (decimal numbers are not integers) in the array realNumberArray and store the new array in the variable squaredIntegers.
Compute and square values from the realNumberArray and store them in the variable squaredIntegers using the map(), filter(), and/or reduce() functions.
const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]; const squareList = (arr) => {  "use strict";  const squaredIntegers = arr.filter( (num) => num > 0 && num % parseInt(num) === 0 ).map( (num) => Math.pow(num, 2) );  return squaredIntegers; }; const squaredIntegers = squareList(realNumberArray); console.log(squaredIntegers); //returns [16, 1764, 36]
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
let weasleys = ["Bill", "Charlie", "Percy", "Fred", "George", "Ron", "Ginny"]; const siblings = weasleys.filter(numberOfWords => numberOfWords.length > 5); console.log(siblings); (2) ["Charlie", "George"]
The map() method creates a new array with the results of calling a provided function on every element in the calling array. 
var array1 = [1, 4, 9, 16]; // pass a function to map const map1 = array1.map(x => x * 2); console.log(map1); // expected output: Array [2, 8, 18, 32]
Map and Filter info is from MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
var charas = [  {    name: "Albus Dumbledore",    wandCore: "thestral tail hair",    wandWood: "elder"  },  {    name: "Bellatrix Lestrange",    wandCore: "dragon heartstring",    wandWood: "walnut"  },  {    name: "Cedric Diggory",    wandCore: "unicorn hair",    wandWood: "ash"  },  {    name: "Dolores Umbridge",    wandCore: "dragon heartstring",    wandWood: "birch"  },  {    name: "Draco Malfoy",    wandCore: "unicorn hair",    wandWood: "hawthorn"  },  {    name: "Fleur Delacour",    wandCore: "veela hair",    wandWood: "rosewood"  },  {    name: "Gilderoy Lockhart",    wandCore: "dragon heartstring",    wandWood: "cherry"  },  {    name: "Horace Slughorn",    wandCore: "dragon heartstring",    wandWood: "cedar"  },  {    name: "Neville Longbottom",    wandCore: "unicorn hair",    wandWood: "cherry"  },  {    name: "Peter Pettigrew",    wandCore: "dragon heartstring",    wandWood: "chestnut"  },  {    name: "Charlie Weasley",    wandCore: "unicorn hair",    wandWood: "ash"  },  {    name: "Ron Weaslet",    wandCore: "unicorn hair",    wandWood: "willow"  },  {    name: "Viktor Krum",    wandCore: "dragon heartstring",    wandWood: "hornbeam"  } ]; //filter or look through the charas array //return only the objects in the charas array that have wandCore equal to "dragon heartstring" var dragonHeartstring = charas.filter(wand => wand.wandCore === "dragon heartstring"); console.log(dragonHeartstring);
console.log(dragonHeartstring); returns:
Tumblr media
//map doesn't change the original array, it will create a new array //use map to get all the names in the charas array var hpNames = charas.map(names => names.name); console.log(hpNames);
console.log(hpNames); will return:
Tumblr media
//use map to lowercase all the names in the charas array var lowercaseNames = charas.map(lowercase => lowercase.name.toLowerCase()); console.log(lowercaseNames); (13) ["albus dumbledore", "bellatrix lestrange", "cedric diggory", "dolores umbridge", "draco malfoy", "fleur delacour", "gilderoy lockhart", "horace slughorn", "neville longbottom", "peter pettigrew", "charlie weasley", "ron weaslet", "viktor krum"]
map() is similar to for loops. It will iterate over an array then create or return a new array. Each item of the array will be passed through a function.
var blacks = ["Sirius", "Regulus", "Walburga", "Orion"]; //add a last name to each of the contents of the blacks array var blackFamily = blacks.map(name => `${name} Black`); console.log(blackFamily); (4) ["Sirius Black", "Regulus Black", "Walburga Black", "Orion Black"]
For more info about map(), refer to this: https://www.freecodecamp.org/forum/t/javascript-array-prototype-map/14294
//modify the contents of an object inside an array //add new properties to an array var students = [  {    firstName: "Percy",    lastName: "Weasley",    house: "Gryffindor"  },  {    firstName: "Padma",    lastName: "Patil",    house: "Ravenclaw"  },  {    firstName: "Pansy",    lastName: "Parkinson",    house: "Slytherin"  } ]; var hogwartsStudents = students.map(arr => {  var newObject = {};  newObject[arr.firstName] = arr.lastName;  newObject.school = "Hogwarts";  newObject.bloodStatus = "Pureblood";  return newObject; }); console.log(hogwartsStudents);
Tumblr media
var hogwarts = students.map(arr => {  var {...student} = arr;  return {    ...student,    school: "Hogwarts",    pureblood: true,  }; }); console.log(hogwarts);
Tumblr media
reduce() will apply a function to all the contents of an array then return a single value.
For more info about reduce(), refer to this: https://code.tutsplus.com/tutorials/how-to-use-map-filter-reduce-in-javascript--cms-26209 and http://engineering.khanacademy.org/posts/lets-reduce.htm
Tumblr media
//add all the values in an array of objects //supply an initial value (0) so that each item will be passed through the function var initialValue = 0; var randomAges = [  {    name: "Daphne",    age: 12  },  {    name: "Astoria",    age: 11  },  {    name: "Pansy",    age:13  },  {    name: "Millicent",    age: 15  } ] var totalAge = randomAges.reduce((accumulator, currentValue) => accumulator + currentValue.age, initialValue); console.log(totalAge); //returns 51 //accumulator is also like the previous value, at the beginning, it will be the initial value //current value is for iterating through the array //0 + 12 = 12 //12 + 11 = 23 //23 + 13 = 36 //36 + 15 = 51 51
Default Parameters for Functions
Tumblr media
const welcomeMessage = (name = "Unknown") => {  return `Hello, ${name}. Welcome to Hogwarts School of Witchcraft and Wizardry.`; } console.log(welcomeMessage("Percy")); //returns Hello, Percy. Welcome to Hogwarts School of Witchcraft and Wizardry. console.log(welcomeMessage()); //returns Hello, Unknown. Welcome to Hogwarts School of Witchcraft and Wizardry.
//add default parameters so that the function will add 1 to number if value is not specified. The default parameter for value should be 1 const increment = (function() {  "use strict";  return function increment(number, value = 1) {    return number + value;  }; })(); console.log(increment(5, 2)); // returns 7 since the function adds number and value console.log(increment(5)); // returns 6. Value defaults to 1 since the value wasn't specified
Use the Rest Operator with Function Parameters
Use the rest operator to “create functions that take a variable number of arguments. These arguments are stored in an array that can be accessed later from inside the function.”
Tumblr media
... - spread operator
Modify the function sum so that it uses the rest operator and it works in the same way with any number of parameters.
const sum = (function() {  "use strict";  return function sum(... args) { //use the spread operator ... on the args parameter    return args.reduce((a, b) => a + b, 0);  }; })(); //or: function sum(...args) {    return args.reduce((a, b) => a + b, 0); } console.log(sum(1, 2, 3)); // 6 console.log(sum(0, 1, 2)); // 3 console.log(sum(1, 2, 3, 4)); //10 console.log(sum(5)); // 5 console.log(sum()); // 0
//use ... for rest operator //(...siblings) is example of rest operator. It creates an array, where the arguments for the function are stored var siblings = ((...siblings) => `The following characters are siblings: ${siblings}`); var weasleySiblings = ["Bill", "Charlie", "Fred", "George", "Percy", "Ron", "Ginny"]; console.log(siblings(weasleySiblings)); The following characters are siblings: Bill,Charlie,Fred,George,Percy,Ron,Ginny console.log(siblings("Parvati", "Padma")); The following characters are siblings: Parvati,Padma console.log(siblings("Daphne", "Astoria")); The following characters are siblings: Daphne,Astoria
function ravenclaw(...students) {  return `The following students are from Ravenclaw House: ${students}`; } ravenclaw("Cho", "Luna", "Padma", "Terry", "Marietta", "Roger", "Anthony", "Michael"); "The following students are from Ravenclaw House: Cho,Luna,Padma,Terry,Marietta,Roger,Anthony,Michael"
Use the Spread Operator to Evaluate Arrays In-Place
spread operator - allows you to “expand arrays and other expressions in places where multiple parameters or elements are expected.”
Tumblr media
//copy all contents of 1 array into another using the spread operator const founders = ['Salazar', 'Rowena', 'Helga', 'Godric']; let hogwartsFounders; (function() {  "use strict";  hogwartsFounders = [...founders]; })(); console.log(hogwartsFounders); (4) ["Salazar", "Rowena", "Helga", "Godric"]
//add elements to an existing array using spread operator var owls = ["Hedwig", "Pigwidgeon"]; var pets = [...owls, "Scabbers", "Trevor"]; console.log(pets); ["Hedwig", "Pigwidgeon", "Scabbers", "Trevor"]
//use spread operator to pass elements of an array to a function as separate arguments var add = (a, b, c) => a + b + c; var sampleArguments = [1, 2, 3]; add(...sampleArguments); 6
This is the same as the code above: function add(a, b, c) {  return a + b + c ; } var sampleArguments = [1, 2, 3]; add(...sampleArguments); 6
Use Destructuring Assignment to Assign Variables from Objects
Destructuring assignment is special syntax for neatly assigning values taken directly from an object to variables.
Tumblr media
var twins = {  weasleys: ["Fred", "George"],  patils: ["Padma", "Parvati"],  prewetts: ["Fabian", "Gideon"] }; var {weasleys, patils, prewetts} = twins; weasleys (2) ["Fred", "George"] patils (2) ["Padma", "Parvati"] prewetts (2) ["Fabian", "Gideon"] console.log(weasleys); (2) ["Fred", "George"]
//store the value of twins somewhere else: var {weasleys: weasleyTwins, patils: patilTwins, prewetts: prewettTwins} = twins; weasleyTwins (2) ["Fred", "George"] patilTwins (2) ["Padma", "Parvati"] prewettTwins (2) ["Fabian", "Gideon"] console.log(prewettTwins); (2) ["Fabian", "Gideon"]
Use destructuring to obtain the average temperature for tomorrow from the input object AVG_TEMPERATURES, and assign value with key tomorrow to tempOfTomorrow in line.
const AVG_TEMPERATURES = {  today: 77.5,  tomorrow: 79 }; function getTempOfTmrw(avgTemperatures) {  "use strict";  const {tomorrow: tempOfTomorrow} = avgTemperatures;  return tempOfTomorrow; } console.log(getTempOfTmrw(AVG_TEMPERATURES)); //returns 79
var hogwartsInfo = {  headmaster: "Dumbledore",  deputyHeadmistress: "McGonagall" }; var durmstrangInfo = {  headmaster: "Karkaroff",  student: "Krum" } var beauxbatonsInfo = {  headmaster: "Maxime",  student: "Delacour" } var getSchoolHeadmaster = (hm) => {  "use strict";  var {headmaster: schoolHeadmaster} = hm;  return schoolHeadmaster; } console.log(getSchoolHeadmaster(hogwartsInfo)); //returns Dumbledore console.log(getSchoolHeadmaster(beauxbatonsInfo)); //returns Maxime console.log(getSchoolHeadmaster(durmstrangInfo)); //returns Karkaroff
You can use the above function to get the headmaster property of any object as long as it has said property.
It’s also possible to “destructure nested objects into variables”
Tumblr media
Use destructuring assignment to obtain max of forecast.tomorrow and assign it to maxOfTomorrow.
const LOCAL_FORECAST = {  today: { min: 72, max: 83 },  tomorrow: { min: 73.3, max: 84.6 } }; function getMaxOfTmrw(forecast) {  "use strict";  const {tomorrow: {max: maxOfTomorrow}} = forecast;  return maxOfTomorrow; } console.log(getMaxOfTmrw(LOCAL_FORECAST)); // returns 84.6
var harryPotter = {  fullName: {first: "Harry", last: "Potter"},  wand: {wood: "Holly", core: "Phoenix Feather"} }; var dracoMalfoy = {  fullName: {first: "Draco", last: "Malfoy"},  wand: {wood: "Hawthorn", core: "Unicorn Hair"} }; var hermioneGranger = {  fullName: {first: "Hermione", last: "Granger"},  wand: {wood: "Vine", core: "Dragon Heartstring"} }; var getWandCore = (core) => {  "use strict";  var {wand: {core: wandCore}} = core;  return wandCore; } console.log(getWandCore(harryPotter)); //returns Phoenix Feather console.log(getWandCore(dracoMalfoy)); //returns Unicorn Hair console.log(getWandCore(hermioneGranger)); //returns Dragon Heartstring var getWandWood = (wood) => {  "use strict";  var {wand: {wood: wandWood}} = wood;  return wandWood; } console.log(getWandWood(harryPotter)); //returns Holly console.log(getWandWood(dracoMalfoy)); //returns Hawthorn console.log(getWandWood(hermioneGranger)); //returns Vine
The above functions will let you get the wood and core of a wand.
Use Destructuring Assignment to Assign Variables from Arrays
You can also destructure arrays.
One key difference between the spread operator and array destructuring is that the spread operator unpacks all contents of an array into a comma-separated list. Consequently, you cannot pick or choose which elements you want to assign to variables.
Tumblr media
Use destructuring assignment to swap the values of a and b so that a receives the value stored in b, and b receives the value stored in a.
let a = 8, b = 6; (() => {  "use strict";  [b, a] = [a, b]; })(); console.log(a); // should be 6 console.log(b); // should be 8
Use Destructuring Assignment with the Rest Operator to Reassign Array Elements
Tumblr media
Use destructuring assignment with the rest operator to perform an effective Array.prototype.slice()so that arr is a sub-array of the original array source with the first two elements omitted.
const source = [1,2,3,4,5,6,7,8,9,10]; function removeFirstTwo(list) {  "use strict";  const [a, b, ...arr] = source;  return arr; } const arr = removeFirstTwo(source); console.log(arr); // should be [3,4,5,6,7,8,9,10] console.log(source); // should be [1,2,3,4,5,6,7,8,9,10];
var blackFamily = ["Sirius", "Andromeda", "Regulus", "Narcissa", "Bellatrix"]; var removeNotDisowned = (family) => {  "use strict";  var [s, a, ...members] = family;  return members; } var notDisownedBlacks = removeNotDisowned(blackFamily); console.log(notDisownedBlacks); //returns Regulus,Narcissa,Bellatrix console.log(blackFamily); //returns Sirius,Andromeda,Regulus,Narcissa,Bellatrix
var magicalItems = ["Sorting Hat", "Gryffindor's Sword", "Slytherin's Locket", "Hufflepuff's Cup", "Ravenclaw's Diadem"]; //This function will remove the first two items from an array and return the remaining items var removeNotHorcruxes = (horcrux) => {  "use strict";  var [a, b, ...items] = horcrux;  return items; } var horcruxes = removeNotHorcruxes(magicalItems); console.log(horcruxes); //returns Slytherin's Locket,Hufflepuff's Cup,Ravenclaw's Diadem var magicalItems2 = ["Time Turner", "Elder Wand", "Tom Riddle's Diary", "Marvolo Gaunt's Ring"]; var horcruxes2 = removeNotHorcruxes(magicalItems2); console.log(horcruxes2); //returns Tom Riddle's Diary,Marvolo Gaunt's Ring
For more info about destructuring, refer to this: https://wesbos.com/destructuring-objects/ and https://hackernoon.com/understanding-the-destructuring-assignment-syntax-in-javascript-c3bf8e1e908a
0 notes
swarnalata31techiio · 3 years ago
Text
How does Typescript compare to Javascript?
About Javascript
JavaScript (JS) is the most popular programming language in the world. It is considered a high-level language that helps to create interactive and dynamic web pages. Together with HTML and CSS, JavaScript is also one of the core technologies for web applications and is highly characterized by its dynamic typing and just-in-time (JIT) compiler. JavaScript started standing out as a server-side technology mainly due to the development and popularity of Node.js. Nonetheless, it is not easy to handle large and complex applications in JavaScript because, as the code grows, it becomes harder to maintain and reuse. Thus, despite the benefits, JavaScript on the server (backend) also made things messier and more complicated to handle. To overcome this struggle, Microsoft introduced TypeScript.
About Typescript
As mentioned, JavaScript can manage hundreds of code lines, but it was not developed to handle very extensive and complex applications. Therefore, TypeScript (TS) is a superset of JavaScript, fulfilling the same purpose as JavaScript. Yet, it was created to handle and develop larger applications by being strongly typed and by including compile-time error controls.
Is JavaScript an object-oriented programming (OOP) language?
ECMAScript is a standard for scripting languages; it provides rules, guidelines, and other details describing what a scripting language should entail. JavaScript is a scripting language that conforms with ECMAScript specifications. Those specifications can change, and new ones can be introduced; hence, there are several ECMAScript versions. One of the versions that introduced the most significant modifications was ECMAScript 6 (also known as ES6 or ECMAScript 2015). This version introduced modules, classes, arrow functions, enhanced object properties, and other exciting features.Upon JavaScript's release of ES6, the concept of classes was indeed introduced. However, this is a syntax feature for JavaScript's prototypal inheritance. JS is prototype-based, not class-based. Hence, JavaScript is not considered a pure object-oriented programming language, despite the ability to follow some object-oriented programming principles.
Is JavaScript an object-oriented programming (OOP) language?
ECMAScript is a standard for scripting languages; it provides rules, guidelines, and other details describing what a scripting language should entail. JavaScript is a scripting language that conforms with ECMAScript specifications. Those specifications can change, and new ones can be introduced; hence, there are several ECMAScript versions. One of the versions that introduced the most significant modifications was ECMAScript 6 (also known as ES6 or ECMAScript 2015). This version introduced modules, classes, arrow functions, enhanced object properties, and other exciting features.Upon JavaScript's release of ES6, the concept of classes was indeed introduced. However, this is a syntax feature for JavaScript's prototypal inheritance. JS is prototype-based, not class-based. Hence, JavaScript is not considered a pure object-oriented programming language, despite the ability to follow some object-oriented programming principles.
Is TypeScript an object-oriented programming (OOP) language?
The answer to this question is not that straightforward. On the one hand, TypeScript has classes and other features that allow the developer to follow OOP principles and techniques.On the other hand, it is not an opinionated language, meaning that it does not "force" the developer to follow object-oriented principles, like certain languages do (e.g., Java and C#). Therefore, TS is usually not considered a pure object-oriented programming language.In fact, instead of object-oriented code, in TypeScript, the developer can also opt for imperative or functional code. Consequently, as mentioned before, both JavaScript and TypeScript are multi-paradigm languages. TypeScript vs JavaScript: code examples.
TypeScript vs JavaScript: which one to learn?
To learn TypeScript, developers must first learn JavaScript. The more a developer knows about JavaScript, the easier it will be to learn TypeScript since both languages share the same syntax as well as the same run-time behavior (except the fact that TS has a compile-time checker).As the most popular language, JavaScript has a lot of available resources and a massive community. In most cases, TypeScript developers can also benefit from those resources since the way tasks are executed will be the same.
1 note · View note