google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






Kĩ thuật lập trình JavaScript giản lược cần biết Trong các bài viết trước jsB@nk đã giới thiệu với bạn rất nhiều kĩ thuật lập trình JavaScript hữu ích:
- Các kĩ thuật viết mã JavaScript giản lược thiết yếu
- Các thủ thuật JavaScript và jQuery hữu ích
- Vài hướng dẫn JavaScript cơ bản để tối ưu hóa hiệu suất trang web

Hôm nay trong bài viết này, jsB@nk muốn đề cập đến các kĩ thuật lập trình JavaScript giản lược (shorthand); các kĩ thuật này cực kì hữu ích trong việc cải thiện hiệu suất ứng dụng JavaScript, nâng cao kĩ năng lập trình JavaScript mà mỗi lập trình viên JavaScript cần nắm vững.

Bạn đã sẵn sàng để đọc thêm chưa? Hãy để lại bất cứ đề nghị nào trong phần bình luận.


Miễn phí web hosting 1 năm đầu tại iPage



Nếu bạn vẫn còn đang tìm kiếm một nhà cung cấp hosting đáng tin cậy, tại sao không dành chút thời gian để thử với iPage, chỉ với không quá 40.000 VNĐ/tháng, nhưng bạn sẽ được khuyến mãi kèm với quà tặng trị giá trên 10.000.0000 VNĐ nếu thanh toán cho 24 tháng ~ 900.000 VNĐ?

Có trên 1 triệu khách hàng hiện tại của iPage đã & đang hài lòng với dịch vụ, tuyệt đối chắc chắn bạn cũng sẽ hài lòng giống họ! Quan trọng hơn, khi đăng ký sử dụng web hosting tại iPage thông qua sự giới thiệu của chúng tôi, bạn sẽ được hoàn trả lại toàn bộ số tiền bạn đã sử dụng để mua web hosting tại iPage. Wow, thật tuyệt vời! Bạn không phải tốn bất kì chi phí nào mà vẫn có thể sử dụng miễn phí web hosting chất lượng cao tại iPage trong 12 tháng đầu tiên. Chỉ cần nói chúng tôi biết tài khoản của bạn sau khi đăng ký.

Nếu muốn tìm hiểu thêm về ưu / nhược điểm của iPage, bạn hãy đọc đánh giá của ChọnHostViệt.com nhé!
Thử iPage miễn phí cho năm đầu tiên NGAY

This really is a must read for any JavaScript based developer. I have made this post as a vital source of reference for learning shorthand JavaScript coding techniques. I have shown you the longhanded versions as well to give some coding perspective.

  • Step 1 – Learn the JavaScript shorthand techniques.
  • Step 2 – Save valuable coding time by keeping your code to a minimum.
  • Step 3 – Impress your colleagues with your awesome coding skills.

It’s as easy as 1,2,3. Here they are.


1. If true … else Shorthand

This is a great code saver for when you want to do something if the test is true, else do something else by using the ternary operator.

Longhand:

var big;
if (x > 10) {
    big = true;
}
else {
    big = false;
}

Shorthand:

var big = (x > 10) ? true : false;

If you rely on some of the weak typing characteristics of JavaScript, this can also achieve more concise code. For example, you could reduce the preceding code fragment to this:

var big = (x > 10);

2. Null, Undefined, ” Checks Shorthand

When creating new variables sometimes you want to check if the variable your referencing for it’s value isn’t null or undefined. I would say this is a very common check for JavaScript coders.

Longhand:

if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
     var variable2 = variable1;
}

Shorthand:

var variable2 = variable1  || '';

Don’t believe me? Test it yourself (paste into Firebug and click run):

//null value example
var variable1 = null;
var variable2 = variable1  || '';
console.log(variable2);
//output: '' (an empty string)

//undefined value example
var variable1 = undefined;
var variable2 = variable1  || '';
console.log(variable2);
//output: '' (an empty string)

//normal value example
var variable1 = 'hi there';
var variable2 = variable1  || '';
console.log(variable2);
//output: 'hi there'

3. Object Array Notation Shorthand

Useful way of declaring small arrays on one line.

Longhand:

var a = new Array();
a[0] = "myString1";
a[1] = "myString2";
a[2] = "myString3";

Shorthand:

var a = ["myString1", "myString2", "myString3"];

4. Associative Array Notation Shorthand

The old school way of setting up an array was to create a named array and then add each named element one by one. A quicker and more readable way is to add the elements at the same time using the object literal notation.

Longhand:

var skillSet = new Array();
skillSet['Document language'] = 'HTML5';
skillSet['Styling language'] = 'CSS3';
skillSet['Javascript library'] = 'jQuery';
skillSet['Other'] = 'Usability and accessibility';

Shorthand:

var skillSet = {
    'Document language' : 'HTML5',
    'Styling language' : 'CSS3',
    'Javascript library' : 'jQuery',
    'Other' : 'Usability and accessibility'
};

Dont forget to omit the final comma otherwise certain browsers will complain (not naming any names, IE).


5. charAt() Shorthand

You can use the eval() function to do this but this bracket notation shorthand technique is much cleaner than an evaluation, and you will win the praise of colleagues who once scoffed at your amateur coding abilities!

Longhand:

"myString".charAt(0);

Shorthand:

"myString"[0]; // Returns 'm'

6. Assignment Operators Shorthand

Assignment operators are used to assign values to JavaScript variables and no doubt you use arithmetic everyday without thinking (no matter what programming language you use Java, PHP, C++ it’s essentially the same principle).

Longhand:

x=x+1;
minusCount = minusCount - 1;
y=y*10;

Shorthand:

x++;
minusCount --;
y*=10;

Other shorthand operators, given that x=10 and y=5, the table below explains the assignment operators:

x += y //result x=15
x -= y //result x=5
x *= y //result x=50
x /= y //result x=2
x %= y //result x=0

7. Regex Object Shorthand

In Javascript, a Regex object can be called like a function like so:

/test/("is test in here")

As opposed to the more verbose(but sometimes more appropriate in cases that you are reusing the Regex).

Longhand:

searchText = "padding 1234 rocket str austin TX 78704 more padding"
/\d+.+\n{0,2}.+\s+[A-Z]{2}\s+\d{5}/m(searchText)
//returns: ["1234 rocket str austin TX 78704"]

Shorthand:

var re = new RegExp(/\d+.+\n{0,2}.+\s+[A-Z]{2}\s+\d{5}/m);
re.exec(searchText);
//returns: ["1234 rocket str austin TX 78704"]

8. If Presence Shorthand

This might be trivial, but worth a mention. When doing “if checks” assignment operators can sometimes be ommited.

Longhand:

if (likeJavaScript == true)

Shorthand:

if (likeJavaScript)

Here is another example. If “a” is NOT equal to true, then do something.

Longhand:

var a;
if ( a != true ) {
// do something...
}

Shorthand:

var a;
if ( !a ) {
// do something...
}

9. Function Variable Arguments Shorthand

Object literal shorthand can take a little getting used to, but seasoned developers usually prefer it over a series of nested functions and variables. You can argue which technique is shorter, but I enjoy using object literal notation as a clean substitute to functions as constructors.

Longhand:

function myFunction( myString, myNumber, myObject, myArray, myBoolean ) {
	// do something...
}
myFunction( "String", 1, [], {}, true );

Shorthand (looks long but only because I have console.log’s in there!):

function myFunction() {
	console.log( arguments.length ); // Returns 5
	for ( i = 0; i < arguments.length; i++ ) {
		console.log( typeof arguments[i] ); // Returns string, number, object, object, boolean
	}
}
myFunction( "String", 1, [], {}, true );

10. JavaScript foreach Loop Shorthand

This little tip is really useful if you want plain JavaScript and hence can’t use the awesome jQuery.each.

Longhand:

for (var i = 0; i < allImgs.length; i++)

Shorthand:

for(var i in allImgs)

11. Suggest one?

I really do love these and would love to find more, please leave a comment!

iPhoneKer.com
Save up to 630$ when buy new iPhone 15

GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project

https://tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools

chatGPTaz.com, chatGPT4.win, chatGPT2.fun, re-chatGPT.com
Talk to ChatGPT by your mother language

Dall-E-OpenAI.com
Generate creative images automatically with AI

AIVideo-App.com
Render creative video automatically with AI

JavaScript theo ngày


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web