Workshop JavaScript Testing. Frameworks. Client vs Server Testing. Jasmine. Chai. Nock. Sinon. Spec Runners: Karma. TDD. Code coverage. Building a testable JS app.
Presentado por ing: Raúl Delgado y Mario García
Workshop JavaScript Testing. Frameworks. Client vs Server Testing. Jasmine. Chai. Nock. Sinon. Spec Runners: Karma. TDD. Code coverage. Building a testable JS app.
Presentado por ing: Raúl Delgado y Mario García
AngularJS with TypeScript and Windows Azure Mobile ServicesRainer Stropek
In the coming two weeks I will do a series of talks at various conferences in Austria and Germany. I will speak about AngularJS, TypeScript, and Windows Azure Mobile Services. In this blog post I publish the slides and the sample code.
In this meetup Eyal Vardi will talk about Angular 2.0 architecture. The session will focus on the main parts of Angular 2.0:
Application Bootstrap
Angular Compiler
Hierarchical Injector
Component Lifecycle Hooks
Change Detector
Renderer
Angular 2.0 & jQuery
Dynamic component creation
Tips & Tricks
Each part will be explained and analyzed. In some cases we will dive into Angular 2.0 source code. Our purpose is to list the Do's & Don’ts of Angular.
The session is mostly targeted for developers which already have some experience with Angular 2.0.
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
This talk takes a deep dive into asynchronous programming patterns and practices, with an emphasis on the promise pattern.
We go through the basics of the event loop, highlighting the drawbacks of asynchronous programming in a naive callback style. Fortunately, we can use the magic of promises to escape from callback hell with a powerful and unified interface for async APIs. Finally, we take a quick look at the possibilities for using coroutines both in current and future (ECMAScript Harmony) JavaScript.
Software development is riddled with explicit and implicit costs. Every decision you make has a cost attached to it. When you're writing code, you're making an investment, the size of which will for a long time define the costs of your future growth. In this talk you will learn how to see, understand and game some of these forces in your favour.
Powerful JavaScript Tips and Best PracticesDragos Ionita
Javascript Best Practices, IIFE, Immediately invoked function expressions, typeof, instanceof, constructor, random items from an array, generate an array of numbers, append an array to another array, is a number, is an array, remove an item from an array
Good karma: UX Patterns and Unit Testing in Angular with KarmaExoLeaders.com
If you listen to backend developers, they will tell you that writing unit tests is essential to good karma. Pay it forward with tests and get back a reliable application. But getting unit tests running on the front end in a “real” application can be a lot more challenging. This intermediate-beginner level workshop will cover how to get setup for writing unit tests, and how to write front-end and end-to-end oriented unit tests for a variety of use cases all for AngularJS. We will work from a series of use cases, transform those into formal acceptance tests, write failing unit tests and then resolve those tests writing code with Angular, html/jade/css and node.
Presentation by Laura Ferguson and Boris Kan @ Create, inc, 2015
Slides from my Lonestar Ruby Conf 2011 presentation.
*** Video of presentation: http://confreaks.com/videos/2531-lsrc2011-testing-javascript-with-jasmine ***
Agenda:
- Briefly cover why you should unit test
- Discuss what Jasmine is and isn't
- Show syntax with comparisons to RSpec
- Jasmine with:
- Vanilla JavaScript
- Jasmine with jQuery
- Jasmine with Ruby (not Rails)
- Jasmine with Rails
- Evergreen
- capybara-webkit
- Where does CoffeeScript, node.js, etc. fit in?
- Other helpful libraries/Wrap-up
AngularJS with TypeScript and Windows Azure Mobile ServicesRainer Stropek
In the coming two weeks I will do a series of talks at various conferences in Austria and Germany. I will speak about AngularJS, TypeScript, and Windows Azure Mobile Services. In this blog post I publish the slides and the sample code.
In this meetup Eyal Vardi will talk about Angular 2.0 architecture. The session will focus on the main parts of Angular 2.0:
Application Bootstrap
Angular Compiler
Hierarchical Injector
Component Lifecycle Hooks
Change Detector
Renderer
Angular 2.0 & jQuery
Dynamic component creation
Tips & Tricks
Each part will be explained and analyzed. In some cases we will dive into Angular 2.0 source code. Our purpose is to list the Do's & Don’ts of Angular.
The session is mostly targeted for developers which already have some experience with Angular 2.0.
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
This talk takes a deep dive into asynchronous programming patterns and practices, with an emphasis on the promise pattern.
We go through the basics of the event loop, highlighting the drawbacks of asynchronous programming in a naive callback style. Fortunately, we can use the magic of promises to escape from callback hell with a powerful and unified interface for async APIs. Finally, we take a quick look at the possibilities for using coroutines both in current and future (ECMAScript Harmony) JavaScript.
Software development is riddled with explicit and implicit costs. Every decision you make has a cost attached to it. When you're writing code, you're making an investment, the size of which will for a long time define the costs of your future growth. In this talk you will learn how to see, understand and game some of these forces in your favour.
Powerful JavaScript Tips and Best PracticesDragos Ionita
Javascript Best Practices, IIFE, Immediately invoked function expressions, typeof, instanceof, constructor, random items from an array, generate an array of numbers, append an array to another array, is a number, is an array, remove an item from an array
Good karma: UX Patterns and Unit Testing in Angular with KarmaExoLeaders.com
If you listen to backend developers, they will tell you that writing unit tests is essential to good karma. Pay it forward with tests and get back a reliable application. But getting unit tests running on the front end in a “real” application can be a lot more challenging. This intermediate-beginner level workshop will cover how to get setup for writing unit tests, and how to write front-end and end-to-end oriented unit tests for a variety of use cases all for AngularJS. We will work from a series of use cases, transform those into formal acceptance tests, write failing unit tests and then resolve those tests writing code with Angular, html/jade/css and node.
Presentation by Laura Ferguson and Boris Kan @ Create, inc, 2015
Slides from my Lonestar Ruby Conf 2011 presentation.
*** Video of presentation: http://confreaks.com/videos/2531-lsrc2011-testing-javascript-with-jasmine ***
Agenda:
- Briefly cover why you should unit test
- Discuss what Jasmine is and isn't
- Show syntax with comparisons to RSpec
- Jasmine with:
- Vanilla JavaScript
- Jasmine with jQuery
- Jasmine with Ruby (not Rails)
- Jasmine with Rails
- Evergreen
- capybara-webkit
- Where does CoffeeScript, node.js, etc. fit in?
- Other helpful libraries/Wrap-up
Second iteration of my javascript talk.
Presented at PHP Day Italia 2009 on May 15th.
Slides refactored, cut down code examples and added some content about js abstractions and ecmascript 3.1.
See http://federico.galassi.net/2009/05/17/javascript-the-good-parts-talk/
Follow me on Twitter!
https://twitter.com/federicogalassi
Ten useful JavaScript tips & best practicesAnkit Rastogi
In this presentation there are ten useful JavaScript techniques which can be included in your application easily with less friction along with some AngularJs tips and best practices as a bonus. These tips and best practices are accompanied by examples & will cover script loading, design pattern, performance optimization and other areas.
Since best practices are very subjective topics, proper benchmarking needs to be done.
2013-06-15 - Software Craftsmanship mit JavaScriptJohannes Hoppe
Entwickeln Sie Clean Code mit JavaScript. Den “Software Craftsman” zeichnen dabei Wissen, Werkzeuge und Wiederholung aus. Diese drei Grundfeste werden speziell für JavaScript beleuchtet. Lernen Sie die wichtigsten Patterns für eine stabile und wartbare Website kennen. Überprüfen Sie Ihre persönliche Werkzeugkiste für Entwicklung, Testing und Deployment. Schließen Sie Bekanntschaft mit Code Katas für JavaScript.
2013-06-24 - Software Craftsmanship with JavaScriptJohannes Hoppe
Entwickeln Sie Clean Code mit JavaScript. Den “Software Craftsman” zeichnen dabei Wissen, Werkzeuge und Wiederholung aus. Diese drei Grundfeste werden speziell für JavaScript beleuchtet. Lernen Sie die wichtigsten Patterns für eine stabile und wartbare Website kennen. Überprüfen Sie Ihre persönliche Werkzeugkiste für Entwicklung, Testing und Deployment. Schließen Sie Bekanntschaft mit Code Katas für JavaScript.
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6FrontDays
Общий обзор новых возможностей ES6, сравнение с более ранними стандартами. Почему стоит использовать ES6 уже сейчас? Поговорим о таких нововведениях как: поддержка классов, шаблоны строк, модули, стрелочные функции, генераторы и о многом другом.
These are the slides from my YUI3 presentation at Open Hack Day in London.
Code demo can be found here:
http://blog.davglass.com/files/openhackday/openhackday/code/photos/
Things you should know about Javascript ES5. A programming language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else
Practical JavaScript Programming - Session 1/8Wilson Su
JavaScript is one of the most popular skills in today’s job market. It allows you to create both client- and server-side applications quickly and easily. Having a solid understanding of this powerful and versatile language is essential to anyone who uses it.
“Practical JavaScript Programming” does not only focus on best practices, but also introduces the fundamental concepts. This course will take you from JavaScript basics to advanced. You’ll learn about topics like Data Types, Functions, Events, AJAX and more.
The next version of JavaScript, ES6, is starting to arrive. Many of its features are simple enhancements to the language we already have: things like arrow functions, class syntax, and destructuring. But other features will change the way we program JavaScript, fundamentally expanding the capabilities of the language and reshaping our future codebases. In this talk we'll focus on two of these, discovering the the myriad possibilities of generators and the many tricks you can pull of with template strings.
Similar to Workshop 1: Good practices in JavaScript (20)
Workshop Isomorphic Web Apps with ReactJS:
- Universal web apps - Isomorphic
- Server Side Rendering (SSR) with ReactJS
- Server Side Rendering with Redux
- Server Side Rendering with React Router
- Server Side Rendering: server.js - Main Entry Point
- Server Side Rendering: server.js - HTML Template
- Client main entry point: client.js
- Webpack bundles
- Avoiding FOUC - Webpack ExtractTextPlugin
- Webpack code splitting
- React Router - Configuration with Plain Routes
- React Router - Dynamic Routing & WebPack
- Dynamic Routing with new Reducers
- Combining new Reducers - ReducerRegistry
- Data fetching before rendering
- React Router + Redux + Redial: Server Side
- React Router + Redux + Redial: provideHooks
- React Router + Redux + Redial: Client Side
- SEO friendly universal web apps - React-Helmet
- React-Helmet - Server Side Rendering
Presentado por ingeniero: Marc Torrent
http://www.visual-engin.com/blog/testing-protocolos-y-extensiones-ios-workshop/
Workshop Testing, protocolos y extensiones:
- Objetivos
- Requisitios
- Protocols
- Configurar proyecto en xcode
- Tests unitarios
- Integración continua
- Material de interés
Presentado por ingenieros Alberto Irurueta y Alejandro García
Workshop fundamentos de Swift:
- Language Basics
- Playgrounds
- Variables
- Functions
- Optionals
- Control Flow
Presentado por nuestros ingenieros Alberto Irurueta y Pia Muñoz.
Workshop Apps with ReactNative III:
- React Native short Recap
- The Native Side
- Building Native Modules (iOS & Android)
- Building Native Components (iOS & Android)
Presentado por ingenieros Alberto Irurueta y Enrique Oriol
Workshop Apps with ReactNative II:
- React Native short Recap
- Navigation in React Native Apps
- Tabs & Other Architectural Components
- Lists & Other Presentational Components
- OpenSource Important Components
Presentado por ingenieros Raúl Delgado y Marc Torrent
Workshop Apps with ReactNative I:
- What is React Native?
- Native Components
- Asynchronous execution
- Debugging
- Live Reload/Hot reload
- Flexbox and styling
- It’s just a JS framework!
- Native Components
- Native APIs
- Native modules
- Some Thoughts on Production Development
Presentado por ingeniero Jordi Serra
Workshop: EmberJS - In Depth
- Ember Data - Adapters & Serializers
- Routing and Navigation
- Templates
- Services
- Components
- Integration with 3rd party libraries
Presentado por ingenieros: Mario García y Marc Torrent
Advanced Flow Concepts Every Developer Should KnowPeter Caitens
Tim Combridge from Sensible Giraffe and Salesforce Ben presents some important tips that all developers should know when dealing with Flows in Salesforce.
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
Keep tabs on your field staff effortlessly with Informap Technology Centre LLC. Real-time tracking, task assignment, and smart features for efficient management. Request a live demo today!
For more details, visit us : https://informapuae.com/field-staff-tracking/
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
Experience our free, in-depth three-part Tendenci Platform Corporate Membership Management workshop series! In Session 1 on May 14th, 2024, we began with an Introduction and Setup, mastering the configuration of your Corporate Membership Module settings to establish membership types, applications, and more. Then, on May 16th, 2024, in Session 2, we focused on binding individual members to a Corporate Membership and Corporate Reps, teaching you how to add individual members and assign Corporate Representatives to manage dues, renewals, and associated members. Finally, on May 28th, 2024, in Session 3, we covered questions and concerns, addressing any queries or issues you may have.
For more Tendenci AMS events, check out www.tendenci.com/events
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns
Unlocking Business Potential: Tailored Technology Solutions by Prosigns
Discover how Prosigns, a leading technology solutions provider, partners with businesses to drive innovation and success. Our presentation showcases our comprehensive range of services, including custom software development, web and mobile app development, AI & ML solutions, blockchain integration, DevOps services, and Microsoft Dynamics 365 support.
Custom Software Development: Prosigns specializes in creating bespoke software solutions that cater to your unique business needs. Our team of experts works closely with you to understand your requirements and deliver tailor-made software that enhances efficiency and drives growth.
Web and Mobile App Development: From responsive websites to intuitive mobile applications, Prosigns develops cutting-edge solutions that engage users and deliver seamless experiences across devices.
AI & ML Solutions: Harnessing the power of Artificial Intelligence and Machine Learning, Prosigns provides smart solutions that automate processes, provide valuable insights, and drive informed decision-making.
Blockchain Integration: Prosigns offers comprehensive blockchain solutions, including development, integration, and consulting services, enabling businesses to leverage blockchain technology for enhanced security, transparency, and efficiency.
DevOps Services: Prosigns' DevOps services streamline development and operations processes, ensuring faster and more reliable software delivery through automation and continuous integration.
Microsoft Dynamics 365 Support: Prosigns provides comprehensive support and maintenance services for Microsoft Dynamics 365, ensuring your system is always up-to-date, secure, and running smoothly.
Learn how our collaborative approach and dedication to excellence help businesses achieve their goals and stay ahead in today's digital landscape. From concept to deployment, Prosigns is your trusted partner for transforming ideas into reality and unlocking the full potential of your business.
Join us on a journey of innovation and growth. Let's partner for success with Prosigns.
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
The European Union Agency for Law Enforcement Cooperation (Europol) has suffered an alleged data breach after a notorious threat actor claimed to have exfiltrated data from its systems. Infamous data leaker IntelBroker posted on the even more infamous BreachForums hacking forum, saying that Europol suffered a data breach this month.
The alleged breach affected Europol agencies CCSE, EC3, Europol Platform for Experts, Law Enforcement Forum, and SIRIUS. Infiltration of these entities can disrupt ongoing investigations and compromise sensitive intelligence shared among international law enforcement agencies.
However, this is neither the first nor the last activity of IntekBroker. We have compiled for you what happened in the last few days. To track such hacker activities on dark web sources like hacker forums, private Telegram channels, and other hidden platforms where cyber threats often originate, you can check SOCRadar’s Dark Web News.
Stay Informed on Threat Actors’ Activity on the Dark Web with SOCRadar!
Modern design is crucial in today's digital environment, and this is especially true for SharePoint intranets. The design of these digital hubs is critical to user engagement and productivity enhancement. They are the cornerstone of internal collaboration and interaction within enterprises.
top nidhi software solution freedownloadvrstrong314
This presentation emphasizes the importance of data security and legal compliance for Nidhi companies in India. It highlights how online Nidhi software solutions, like Vector Nidhi Software, offer advanced features tailored to these needs. Key aspects include encryption, access controls, and audit trails to ensure data security. The software complies with regulatory guidelines from the MCA and RBI and adheres to Nidhi Rules, 2014. With customizable, user-friendly interfaces and real-time features, these Nidhi software solutions enhance efficiency, support growth, and provide exceptional member services. The presentation concludes with contact information for further inquiries.
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
Your Digital Assistant.
Making complex approach simple. Straightforward process saves time. No more waiting to connect with people that matter to you. Safety first is not a cliché - Securely protect information in cloud storage to prevent any third party from accessing data.
Would you rather make your visitors feel burdened by making them wait? Or choose VizMan for a stress-free experience? VizMan is an automated visitor management system that works for any industries not limited to factories, societies, government institutes, and warehouses. A new age contactless way of logging information of visitors, employees, packages, and vehicles. VizMan is a digital logbook so it deters unnecessary use of paper or space since there is no requirement of bundles of registers that is left to collect dust in a corner of a room. Visitor’s essential details, helps in scheduling meetings for visitors and employees, and assists in supervising the attendance of the employees. With VizMan, visitors don’t need to wait for hours in long queues. VizMan handles visitors with the value they deserve because we know time is important to you.
Feasible Features
One Subscription, Four Modules – Admin, Employee, Receptionist, and Gatekeeper ensures confidentiality and prevents data from being manipulated
User Friendly – can be easily used on Android, iOS, and Web Interface
Multiple Accessibility – Log in through any device from any place at any time
One app for all industries – a Visitor Management System that works for any organisation.
Stress-free Sign-up
Visitor is registered and checked-in by the Receptionist
Host gets a notification, where they opt to Approve the meeting
Host notifies the Receptionist of the end of the meeting
Visitor is checked-out by the Receptionist
Host enters notes and remarks of the meeting
Customizable Components
Scheduling Meetings – Host can invite visitors for meetings and also approve, reject and reschedule meetings
Single/Bulk invites – Invitations can be sent individually to a visitor or collectively to many visitors
VIP Visitors – Additional security of data for VIP visitors to avoid misuse of information
Courier Management – Keeps a check on deliveries like commodities being delivered in and out of establishments
Alerts & Notifications – Get notified on SMS, email, and application
Parking Management – Manage availability of parking space
Individual log-in – Every user has their own log-in id
Visitor/Meeting Analytics – Evaluate notes and remarks of the meeting stored in the system
Visitor Management System is a secure and user friendly database manager that records, filters, tracks the visitors to your organization.
"Secure Your Premises with VizMan (VMS) – Get It Now"
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
Listen to the keynote address and hear about the latest developments from Rachana Ananthakrishnan and Ian Foster who review the updates to the Globus Platform and Service, and the relevance of Globus to the scientific community as an automation platform to accelerate scientific discovery.
Check out the webinar slides to learn more about how XfilesPro transforms Salesforce document management by leveraging its world-class applications. For more details, please connect with sales@xfilespro.com
If you want to watch the on-demand webinar, please click here: https://www.xfilespro.com/webinars/salesforce-document-management-2-0-smarter-faster-better/
1. Front End Workshops
II. (Not so) Basic JavaScript
concepts
Mario García Martín
mgarcia@visual-engin.com
2. Good practices in JavaScript
“Always code as if the guy who ends up maintaining your code will
be a violent psychopath who knows where you live.”
— John Woods
3. Avoid global variables
// homer.js
var isDrunk = true;
// bart.js
var isDrunk = false;
// index.html
<script src=”./homer.js”></script>
<script src=”./bart.js”></script>
console.log(isDrunk);
Global variables and functions can be overwritten by other
scripts.
4. Declare variables with var
Using ‘use strict’ directive will prevent undeclared variable
definitions.
function defineBeer() {
beer = 1;
}
defineBeer();
Not doing so results in global variable declaration.
'use strict';
function defineBeer() {
beer = 1;
}
defineBeer();
Uncaught ReferenceError: beer is
not defined
function defineBeer() {
var beer = 1;
}
defineBeer();
5. Manipulating the DOM
$('#homer).addClass('alcoholic');
// Some logic here...
$('#homer').addClass('angry');
Writing the DOM
Reading the DOM
var $homer = $('#homer');
$homer.addClass('alcoholic');
// Some logic here...
$homer.addClass('angry');
var $ul = $('#target-ul');
for (var i=0; i<4; i++) {
$ul.append('<li>' + i +
'</li>');
}
var html = '';
for (var i=0; i<4; i++) {
html += '<li>' + i + '</li>';
}
$('#target-ul').append(html);
6. Avoid heavy nesting
function logHomerBehaviour(homer) {
if (homer.isAtWork()) {
for (var i=0; i<4; i++) {
if (homer.isAsleep()) {
if (homer.isSnoring()) {
for (var j=0; j<2; j++) {
snore += 'Zz...';
}
console.log(snore);
}
} else {
console.log('Doughnuts!');
}
}
}
}
function logHomerBehaviour(homer) {
if (!homer.isAtWork()) { return; }
for (var i=0; i<4; i++) {
if (homer.isAsleep()) {
logHomerSleeping(homer);
} else {
console.log('Doughnuts!');
}
}
}
function logHomerSleeping(homer) {
if (!homer.isSnoring()) { return; }
console.log('Zz...Zz...');
}
7. Comment your code
“Good code explains itself”.
function handleEvent(ev) {
// In IE9 and earlier, use the window.event.
ev = ev || window.event;
}
Comment what you consider needed, but don’t tell others
your life story.
8. Comment your code
“Good code explains itself”.
function handleEvent(ev) {
// In IE9 and earlier, use the window.event.
ev = ev || window.event;
}
Comment what you consider needed, but don’t tell others
your life story.
9. Other good practices
Avoid eval function
Never pass a string to setTimeout or setInterval
Use === instead of ==
console.log(0 == false); // true
console.log('2' == 2); // true
console.log(0 === false); // false
console.log('2' === 2); // false
Tools: JS Lint
10. The only valid measurement of code quality...
WTFs/minute
11. More information in...
● http://www.slideshare.net/cheilmann/javascript-best-practices-1041724
● https://www.youtube.com/watch?v=hQVTIJBZook
● https://www.devbridge.com/articles/javascript-best-practices/
● http://www.codeproject.com/Articles/580165/JavaScript-Best-Practices
12. (Ir)Regular expressions
“Some people, when confronted with a problem, think ‘I know, I’ll
use regular expressions.’ Now they have two problems.”
— Jamie Zawinski
13. Creating a regular expression
var regexp1 = new RegExp('abc', 'gi');
var regexp2 = /abc/gi;
/abc/ A sequence of characters
/[abc]/ Any character from a set of characters
/[^abc]/ Any character not in a set of characters
/[0-9]/ Any character in a range of characters
/x+/ One or more occurrences of pattern x
/x*/ Zero or more occurrences
/x?/ Zero or one occurrence
/x{2,4}/ Between two and four occurrences
/(abc)/ A group
/a|b|c/ Any one of several patterns
/d/ Any digit character
/w/ An alphanumeric character [a-zA-Z0-9_]
/s/ Any whitespace character
/./ Any character except newlines
/^/ Start of input
/$/ End of input
14. Using a regular expression in JavaScript
/[0-9]/.test('in 1992'); //true
var neighbor = /neighbou?r/;
neighbor.test('neighbour'); // true
neighbor.test('neighbor'); // true
Through the RexExp object
Through the String object
'12345'.match(/(d)(d)+/); // ['12345', '1', '5']
'Homer drinks beer'.search(/beer/); // 13
'Ho+me[]r'.replace(/[^ws]/g, ''); // 'Homer'
'Homer drinks beer'.split(/s/); // ['Homer', 'drinks', 'beer']
var match = /d+/.exec('one two 100');
console.log(match); // ['100']
console.log(match.index); // 8
15. Do not abuse regular expressions...
^(?:(?:(?:0?[13578]|1[02])(/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(/|-
)(?:29|30)))(/|-)(?:[1-9]ddd|d[1-9]dd|dd[1-9]d|ddd[1-
9])$|^(?:(?:0?[1-9]|1[0-2])(/|-)(?:0?[1-9]|1d|2[0-8]))(/|-)(?:[1-
9]ddd|d[1-9]dd|dd[1-9]d|ddd[1-9])$|^(0?2(/|-)29)(/|-
)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:20)?(?:0[48]|[2468][048]|[13579][
26]))$
16. More information in...
● Mastering Regular Expressions, by Jeffrey E.F. Friedl
● Introducing Regular Expressions, by Michael Fitzgerald
● Regular Expressions Cookbook, by Jan Goyvaerts and Steven Levithan
● https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_E
xpressions
● http://eloquentjavascript.net/09_regexp.html
● http://www.cheatography.com/davechild/cheat-sheets/regular-
expressions/
17. Scopes and Closures. Prototype
“First learn computer science and all the theory. Next develop a
programming style. Then forget all that and just hack.”
— George Carrette
18. Lexical scope
In JavaScript, scopes are declared by functions, not by
blocks.
// Global scope
if (true) {
var x =
24;
}
console.log(x);
var x;
if (true) {
x = 24;
}
console.log(x);
Hoisting
19. Lexical scope
var hero = aHero();
var newSaga = function() {
var foil = aFoil();
var saga = function() {
var deed = aDeed();
console.log(hero + deed + foil);
}
}
20. Execution context (in-memory scope)
var hero = randStr();
var newSaga = function() {
var foil = randStr();
var saga = function() {
var deed = randStr();
console.log(hero + deed + foil);
}
saga();
saga();
}
newSaga();
newSaga();
hero = ‘gal’
newSaga = [ Function ]
foil = ‘cow’
saga = [ Function ]
deed = ‘eyes’
foil = ‘cow’
saga = [ Function ]
21. Execution context (in-memory scope)
var hero = randStr();
var newSaga = function() {
var foil = randStr();
var saga = function() {
var deed = randStr();
console.log(hero + deed + foil);
}
saga();
saga();
}
newSaga();
newSaga();
hero = ‘gal’
newSaga = [ Function ]
foil = ‘cow’
saga = [ Function ]
foil = ‘cow’
saga = [ Function ]
deed = ‘tips’
22. Execution context (in-memory scope)
var hero = randStr();
var newSaga = function() {
var foil = randStr();
var saga = function() {
var deed = randStr();
console.log(hero + deed + foil);
}
saga();
saga();
}
newSaga();
newSaga();
hero = ‘gal’
newSaga = [ Function ]
foil = ‘cow’
saga = [ Function ]
foil = ‘cat’
saga = [ Function ]
deed = ‘Rubs’
23. Execution context (in-memory scope)
var hero = randStr();
var newSaga = function() {
var foil = randStr();
var saga = function() {
var deed = randStr();
console.log(hero + deed + foil);
}
saga();
saga();
}
newSaga();
newSaga();
hero = ‘gal’
newSaga = [ Function ]
foil = ‘cow’
saga = [ Function ]
foil = ‘cat’
saga = [ Function ]
deed = ‘Robs’
24. ‘this’ keyword
Invocation as a method
var homer = {
beer: 'Nice to have another one!',
info: function() {
console.log(this === homer);
console.log(this.beer);
}
};
homer.info(); // true, 'Nice to have another one!'
var bart = {
beer: 'Too young'
};
bart.info = homer.info;
bart.info(); // false, 'Too young'
function bar() {
console.log(this);
}
bar(); // global
25. ‘this’ keyword
Invocation as a method
var anum = 0;
var foo = {
anum: 10,
baz: {
anum: 20,
bar: function() {
console.log(this.anum);
}
}
}
foo.baz.bar(); // 20
var hello = foo.baz.bar;
hello(); // 0
var foo = {
baz: function() {
console.log(this);
}
}
foo.baz(); // foo
var anotherBaz = foo.baz;
anotherBaz(); // global
26. ‘this’ keyword
Invocation as a constructor
function Person() {
this.x = 0;
}
var person = new Person();
console.log(person.x); // 0
27. ‘this’ keyword
Invocation with the apply and call methods
function juggle() {
var result = 0;
for (var n = 0; n < arguments.length; n++) {
result += arguments[n];
}
this.result = result;
}
var ninja1 = {};
var ninja2 = {};
juggle.apply(ninja1, [1, 2, 3, 4]); // ninja1.result = 10;
juggle.call(ninja2, 5, 6, 7, 8); // ninja2.result = 26;
28. Closures
Combines two things: a function, and the environment in which that function
was created.
var toast = 'Cheers!';
function makeToast() {
console.log(toast);
}
makeToast();
function
makeToast() { ... }
var toast
29. Closures
var scope = 'global scope';
function checkscope() {
var scope = 'local scope';
function f() { return
scope; }
return f();
}
checkscope(); // 'local scope';
var scope = 'global scope';
function checkscope() {
var scope = 'local scope';
function f() { return
scope; }
return f;
}
var func = checkscope();
func(); // 'local scope';
31. Constructor function
function Animal(_name) {
var name = _name;
this.getName = function() {
console.log('My name is ' + name);
};
this.setName = function(_name) {
name = _name;
};
}
var animal = new Animal('Santa');
animal.getName(); // My name is Santa
animal.setName('New Santa');
animal.getName(); // My name is New Santa
32. Prototype chain
var o = { a: 1 };
// o --> Object.prototype --> null
var a = ['Homer', 'Marge', 'Lisa'];
// a --> Array.prototype --> Object.prototype --> null
function f() { return 2; }
// f --> Function.prototype --> Object.prototype --> null
33. Prototype chain
function Animal(_name) {
// Instance properties can be set on each instance of the class
this.name = _name;
}
// Prototype properties are shared across all instances of the class.
Animal.prototype.getName = function() {
console.log('My name is ' + this.name);
};
var animal = new Animal('Santa');
animal.getName(); // My name is Santa
34. Inheritance
function Cat(_name) {
Animal.call(this, _name);
}
Cat.prototype = new Animal();
Cat.prototype.scratch = function() {
console.log('I love to scratch!');
}
var cat = new Cat('Claws');
cat.getName(); // My name is Claws
cat.scratch(); // I love to scratch!
35. More information in...
● Secrets of the JavaScript Ninja, by John Resig
● Javascript, the definitive guide, by David Flanagan
● Scope & closures, by Kyle Simpson
● http://www.sitepoint.com/demystifying-javascript-variable-scope-
hoisting/
● http://davidshariff.com/blog/what-is-the-execution-context-in-
javascript/
● http://davidshariff.com/blog/javascript-scope-chain-and-closures/
● http://davidshariff.com/blog/javascript-this-keyword/
36. Memory leaks
“‘Yeah, it works but you’re leaking memory everywhere. Perhaps
we should fix that”. I’ll just restart apache every 10 requests.”
— Rasmus Lerdorf
37. Circular references
<div id="target">Element</div>
<script type="text/javascript">
var obj = document.getElementById('target');
document.getElementById('target').property = obj;
obj.bigString = new Array(10000).join('*');
</script>
Example 1
38. Circular references
<div id="target"></div>
<script type="text/javascript">
function myFunction(element) {
this.elementReference = element;
element.property = this;
}
function leak() {
new myFunction(document.getElementById('target'));
}
leak();
</script>
Example 2
39. Closures and circular references
<button id="element">Click Me</button>
<script type="text/javascript">
function outerFunction() {
var obj = document.getElementById('element');
obj.onclick = function innerFunction() {
console.log('Hi! I will leak');
};
obj.bigString = new Array(10000).join('*');
};
outerFunction();
</script>
40. Closures. Break the circular reference
<button id="element">Click Me</button>
<script type="text/javascript">
function outerFunction() {
var obj = document.getElementById('element');
obj.onclick = function innerFunction() {
console.log('Hi! I have avoided the leak');
};
obj.bigString = new Array(10000).join('*'));
obj = null; //This breaks the circular reference
};
outerFunction();
</script>
41. Closures. Add another closure
<button id="element">Click Me</button>
<script type="text/javascript">
function outerFunction() {
var anotherObj = function innerFunction() {
console.log('Hi! I have avoided the leak');
};
(function anotherInnerFunction() {
var obj = document.getElementById('element');
obj.onclick = anotherObj;
})();
};
outerFunction();
</script>
42. Closures. Avoid the initial closure
<button id="element">Click Me</button>
<script type="text/javascript">
function outerFunction() {
var obj = document.getElementById('element');
obj.onclick = doesNotLeak;
}
function doesNotLeak() {
console.log('Hi! I have avoided the leak');
}
outerFunction();
</script>
43. More information in...
● https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Memory_Management
● http://www.ibm.com/developerworks/web/library/wa-memleak/
● https://msdn.microsoft.com/en-us/magazine/ff728624.aspx
44. Thanks for your attention!
Leave your questions on the comments section